Question

If I create a CustomUser model which inherits from django.contrib.auth.models.User, like so:

in models.py

class CustomUser(django.contrib.auth.models.User):
    customfield = TextField()
    ...

Should I still be able to use django.contrib.auth.{authenticate, login, logout} in the normal way? Do I have to make some additional configuration change? I know these methods only work on User objects, but technically my CustomUser is-a User.

Currently, authenticate(username=u, password=p) is always returning None, even with valid credentials.

Was it helpful?

Solution

Since Django 1.5 (officially but it doesn't worked for me) and "stable" in 1.6 there is a functionality to extend the User model in a clean way.

At first:

-> Take care that you load the User model only via:

from django.contrib.auth import get_user_model
User = get_user_model()

-> Once you have built the database theres no easy way to change the User model. The database relations will break and Django / South isn't able to fix it.

-> third party modules have to be compatible with that new layout and refer in it's models to "get_user_model()", too.

You have to add some Code for the admin to respect your new model: See: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model

To Override the model you need to inherit from AbstractBaseUser:

from django.contrib.auth.models import AbstractBaseUser

class MyUser(AbstractBaseUser):
    ...
    date_of_birth = models.DateField()
    height = models.FloatField()
    ...
    REQUIRED_FIELDS = ['date_of_birth', 'height']

AbstractBaseUser provides you all attributes of the default user model. So you don't have to take care of email, username, first_name, last_name, password etc. More info about overriding the user model: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#django.contrib.auth.models.CustomUser

In your settings link your new model:

AUTH_USER_MODEL = 'customauth.MyUser'

Please read the whole documentation of customizing the user model, there are some interesting hints for overriding the default manager, admin forms etc. Just remember that bigger changes in an existing project can be a big pain.

OTHER TIPS

A short overview:
- Extend models.AbstractUser
- Set AUTH_USER_MODEL in settings.py

All details can be found here: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#specifying-a-custom-user-model

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top