I define a custom User model:

from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
   somefield = models.CharField(max_length=60)

and I add AUTH_USER_MODEL to settengs :

AUTH_USER_MODEL = 'userm.CustomUser'

but when I try this command the authenticate function return 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')

and the result of objects.all is:

In [47]: CustomUser.objects.all()
Out[47]: [<CustomUser: admin>, <CustomUser: nima>, <CustomUser: ali>, <CustomUser: root>, <CustomUser: esi>, <CustomUser: sha>]

am I missed something??

有帮助吗?

解决方案

Probably the problem is that the password is not saved correctly with the create method.

Instead try doing this

u=CustomUser.objects.create(username='root1')
u.set_password('root')
u.save()

Then authenticate(username='root1', password='root') will work (at least it worked in my case).

Update: Also, please take a look at the create_user of the 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

So you should not use CustomUser.objects.create to set the password.

其他提示

I think that it is because you have just created an object not saved in Database so authenticate dont return any object. If you debug authenticate method you can see this.

So could you try :

from django.contrib.auth import authenticate
u = CustomUser.objects.create(username='root',password='root')
u.save()
authenticate(username='root', password='root')
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top