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

Django custom user model authentication don't work

我有一个带有自定义用户模型的应用程序 'homepage'。我可以注册新用户并在我的数据库中看到它。

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)

用户始终是 None。 我可以像这样从数据库中检索它:

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

如果 user.password 的值为 1111,那么您最初以某种方式将值存储在 plain test 中; Django 总是会散列密码以进行比较,因为存储的值也应该散列。

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

实际上问题出在 forms.py:

user.set_password('password2')

我应该这样保存密码:

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

现在好了。