Django自定义用户模型身份验证不起作用

时间:2015-11-28 14:10:41

标签: django django-authentication django-users

我有一个应用程序'主页'使用自定义用户模型。我可以注册新用户并在我的数据库中查看。

settings.py

AUTH_USER_MODEL = 'homepage.User'

models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    phone_number = models.CharField(max_length=15, default='')
    birthday = models.DateField(blank=True, null=True)

class Meta:
    db_table = 'auth_user'

views.py

from django.contrib import auth
from django.contrib.auth import get_user_model

def authentication(request):
    username = request.POST.get('username', '') => one
    password = request.POST.get('password', '') => 1111 (not 1111 but hash)
    user = auth.authenticate(username=username, password=password)

    if user is not None:
        auth.login(request, user)

用户始终为无。 我可以像这样从db中检索它:

User = get_user_model()
user = User.objects.get(username='one')
print(user.username) => one
print(user.password) => 1111 (not 1111 but hash)

但我无法登录。如何让它发挥作用?

修改 形式可能有问题吗?

forms.py

from django.contrib.auth.forms import UserCreationForm
from django.db import models
from django.contrib.auth import get_user_model
MyUser = get_user_model()

class RegistrationForm(UserCreationForm):
first_name = forms.CharField()
last_name = forms.CharField()
username = forms.CharField()
password1 = forms.CharField(widget=forms.PasswordInput, 
                            label="Password")          
password2 = forms.CharField(widget=forms.PasswordInput,
                            label="Confirm password")
email = forms.EmailField(widget=forms.EmailInput)
birthday = forms.DateField(widget=extras.SelectDateWidget(years=YEARS))
phone_number = forms.CharField()
captcha = CaptchaField()

def save(self, commit = True):   
    user = MyUser.objects.create_user(self.cleaned_data['username'])
    user.email = self.cleaned_data['email']
    user.first_name = self.cleaned_data['first_name']
    user.last_name = self.cleaned_data['last_name']
    user.birthday = self.cleaned_data['birthday']
    user.phone_number = self.cleaned_data['phone_number']
    user.set_password('password2')

    if commit:
        user.save() 

    return user

2 个答案:

答案 0 :(得分:2)

如果user.password的值是1111,那么您最初以某种方式将该值存储在普通测试中; Django将始终对密码进行哈希处理以进行比较,因为存储的值也应该进行哈希处理。

确保您最初使用user.set_password设置密码,或使用User.objects.create_user创建用户模型。

答案 1 :(得分:0)

实际上form.py中存在问题:

user.set_password('password2')

我应该保存这样的密码:

user.set_password(self.cleaned_data['password2'])

现在好了。