Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django 1.6 authentication in Custom User model

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??

like image 476
nim4n Avatar asked Feb 19 '26 08:02

nim4n


1 Answers

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.

like image 57
Serafeim Avatar answered Feb 22 '26 00:02

Serafeim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!