forms.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #coding=utf-8
  2. from django import forms
  3. from django.contrib.auth.forms import AuthenticationForm
  4. from django.contrib.auth import authenticate, login
  5. from apps.account.tokens import token_generator
  6. class MyAuthenticationForm(AuthenticationForm):
  7. class Meta:
  8. fields = ('username', 'password')
  9. def __init__(self, *args, **kwargs):
  10. self.request = kwargs.pop('request', None)
  11. super(AuthenticationForm, self).__init__(*args, **kwargs)
  12. self.fields['username'].error_messages = {'required': u'请输入账号!'}
  13. self.fields['password'].error_messages = {'required': u'请输入密码!'}
  14. def clean(self):
  15. username = self.cleaned_data.get('username')
  16. password = self.cleaned_data.get('password')
  17. if username and password:
  18. self.user_cache = authenticate(self.request, username=username, password=password)
  19. if self.user_cache is None:
  20. raise forms.ValidationError(
  21. u'用户名或密码错误!',
  22. code='invalid_login',
  23. params={'username': u'账号'},
  24. )
  25. else:
  26. self.confirm_login_allowed(self.user_cache)
  27. else:
  28. raise forms.ValidationError(
  29. u'参数错误',
  30. code='invalid_params'
  31. )
  32. self.access_token = token_generator.make_token(self.user_cache)
  33. return self.cleaned_data