我目前正在测试 django 1.5 及其自定义 USer 模型,但我有一些理解问题,我在我的帐户应用程序中创建了一个 User 类,它看起来像:
class User(AbstractBaseUser):
email = models.EmailField()
activation_key = models.CharField(max_length=255)
is_active = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
我可以正确注册一个用户,该用户存储在我的 account_user 表中。现在,我该如何登录?我试过了
def login(request):
form = AuthenticationForm()
if request.method == 'POST':
form = AuthenticationForm(request.POST)
email = request.POST['username']
password = request.POST['password']
user = authenticate(username=email, password=password)
if user is not None:
if user.is_active:
login(user)
else:
message = 'disabled account, check validation email'
return render(
request,
'account-login-failed.html',
{'message': message}
)
return render(request, 'account-login.html', {'form': form})
但是用户是 None 它呈现登录表单:(为什么我的 autheticate 返回我 None ?知道吗?
表格.py
class RegisterForm(forms.ModelForm):
""" a form to create user"""
password = forms.CharField(
label="Password",
widget=forms.PasswordInput()
)
password_confirm = forms.CharField(
label="Password Repeat",
widget=forms.PasswordInput()
)
class Meta:
model = User
exclude = ('last_login', 'activation_key')
def clean_password_confirm(self):
password = self.cleaned_data.get("password")
password_confirm = self.cleaned_data.get("password_confirm")
if password and password_confirm and password != password_confirm:
raise forms.ValidationError("Password don't math")
return password_confirm
def clean_email(self):
if User.objects.filter(email__iexact=self.cleaned_data.get("email")):
raise forms.ValidationError("email already exists")
return self.cleaned_data['email']
def save(self):
user = super(RegisterForm, self).save(commit=False)
user.password = self.cleaned_data['password']
user.activation_key = generate_sha1(user.email)
user.save()
return user