使用Django 1.5进行身份验证

时间:2012-12-14 17:29:46

标签: django

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

但是用户是无呈现登录表单:( 为什么我的认证归还给我? 有什么想法吗?

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

1 个答案:

答案 0 :(得分:9)

Django documentation有一个很好的使用新自定义用户的例子。

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

我有一个名为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')
相关问题