我正在测试Django 1.5和自定义用户模型,但是我有一些理解问题。我在我的账户应用程序中创建了一个名为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,则会呈现登录表单:( 我的身份验证为什么会返回None? 有任何想法吗?
forms.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
login()
后,您期望发生什么? - Daniel Roseman