from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import AuthenticationForm User = get_user_model() class EmailAuthenticationForm(AuthenticationForm): username = forms.EmailField(label="Email", required=True) password = forms.CharField(label="Password", widget=forms.PasswordInput, required=True) def clean(self): email = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if email and password: try: user = User.objects.get(email=email) if not user.check_password(password): raise forms.ValidationError('请输入一个正确的用户名和密码。注意,两者都区分大小写。') except User.DoesNotExist: raise forms.ValidationError('请输入一个正确的用户名和密码。注意,两者都区分大小写。') return self.cleaned_data