我定义了一个自定义用户模型:
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
somefield = models.CharField(max_length=60)
我将AUTH_USER_MODEL添加到settengs:
AUTH_USER_MODEL = 'userm.CustomUser'
但是当我尝试这个命令时,authenticate函数返回None:
In [36]: from django.contrib.auth import authenticate
In [37]: CustomUser.objects.create(username='root',password='root')
Out[37]: <CustomUser: root>
In [38]: authenticate(username='root', password='root')
和objects.all的结果是:
In [47]: CustomUser.objects.all()
Out[47]: [<CustomUser: admin>, <CustomUser: nima>, <CustomUser: ali>, <CustomUser: root>, <CustomUser: esi>, <CustomUser: sha>]
我错过了什么吗?
答案 0 :(得分:2)
可能问题是使用create
方法无法正确保存密码。
而是尝试这样做
u=CustomUser.objects.create(username='root1')
u.set_password('root')
u.save()
然后
authenticate(username='root1', password='root')
会起作用(至少它适用于我的情况)。
更新:另外,请看一下create_user
django ducmentation custom user:
def create_user(self, email, date_of_birth, password=None):
# [...]
user = self.model(
email=self.normalize_email(email),
date_of_birth=date_of_birth,
)
# Explicitly set password with the set_password method
user.set_password(password)
user.save(using=self._db)
return user
因此,您不应使用CustomUser.objects.create
来设置密码。
答案 1 :(得分:-1)
我认为这是因为您刚刚创建了一个未保存在数据库中的对象,因此进行身份验证不会返回任何对象。如果你调试authenticate方法,你可以看到这个。
你可以尝试一下:
from django.contrib.auth import authenticate
u = CustomUser.objects.create(username='root',password='root')
u.save()
authenticate(username='root', password='root')