12345678910111213141516171819202122232425262728293031323334353637383940 |
- #coding=utf-8
- from django import forms
- from django.contrib.auth.forms import AuthenticationForm
- from django.contrib.auth import authenticate, login
- from apps.account.tokens import token_generator
- class MyAuthenticationForm(AuthenticationForm):
- class Meta:
- fields = ('username', 'password')
- def __init__(self, *args, **kwargs):
- self.request = kwargs.pop('request', None)
- super(AuthenticationForm, self).__init__(*args, **kwargs)
- self.fields['username'].error_messages = {'required': u'请输入账号!'}
- self.fields['password'].error_messages = {'required': u'请输入密码!'}
- def clean(self):
- username = self.cleaned_data.get('username')
- password = self.cleaned_data.get('password')
- if username and password:
- self.user_cache = authenticate(self.request, username=username, password=password)
- if self.user_cache is None:
- raise forms.ValidationError(
- u'用户名或密码错误!',
- code='invalid_login',
- params={'username': u'账号'},
- )
- else:
- self.confirm_login_allowed(self.user_cache)
- else:
- raise forms.ValidationError(
- u'参数错误',
- code='invalid_params'
- )
- self.access_token = token_generator.make_token(self.user_cache)
- return self.cleaned_data
|