使用Django 1.5进行身份验证

时间:2012-12-15 20:17:28

标签: python django

我目前正在测试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})

我可以正确注册新用户

我的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

我的问题是:为什么身份验证会给我None?我知道我正在尝试authenticate()使用电子邮件作为用户名,但这不是使用自定义用户模型的原因之一吗?

0 个答案:

没有答案