5

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

1 回答 1

9

Django文档有一个使用新自定义用户的非常好的示例。

从您的代码中,我看到唯一缺少的是自定义身份验证后端。

我有一个名为 auth.py 的文件。方法“authenticate”和“get_user”是必需的。

from models import User as CustomUser

class CustomAuth(object):

    def authenticate(self, username=None, password=None):
        try:
            user = CustomUser.objects.get(email=username)
            if user.check_password(password):
                return user
        except CustomUser.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            user = CustomUser.objects.get(pk=user_id)
            if user.is_active:
                return user
            return None
        except CustomUser.DoesNotExist:
            return None

然后必须在您的设置文件中指定身份验证后端

AUTHENTICATION_BACKENDS = ('apps.accounts.auth.CustomAuth')
于 2012-12-15T17:38:42.477 回答