【问题标题】:Django custom user model authentication don't workDjango自定义用户模型身份验证不起作用
【发布时间】:2015-11-28 14:10:40
【问题描述】:

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

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)

用户总是无。 我可以像这样从数据库中检索它:

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

【问题讨论】:

    标签: django django-authentication django-users


    【解决方案1】:

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

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

    【讨论】:

    • 实际上它打印的内容类似于:!shgKxtqOpu4lqUAPGFmTcDqho96auPUyKnvOmYkF。如果我这样保存密码,它会打印 1111:user.password = self.cleaned_data['password2'](仅用于测试)
    【解决方案2】:

    其实forms.py有问题:

    user.set_password('password2')
    

    我应该这样保存密码:

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

    现在没事了。

    【讨论】:

      猜你喜欢
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      • 2019-01-23
      • 1970-01-01
      • 2012-05-06
      • 2014-10-14
      相关资源
      最近更新 更多