Categories
Python

Django friday tips: Switch the user model

In the most recent versions of django, you’re no longer attached to the default user model. So unlike what happened some time ago, when you had two models (User and Profile) “linked” together through an one-to-one relationship, nowadays you can extend or substitute the base user model.

It is as simples as adding the following line to your settings.py:

AUTH_USER_MODEL = 'djangoapp.UserModel'

If you only want to extend it and avoid having to implement some boilerplate, you should sub class the AbstractUserModel like this:

from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
    ...

This way you will be able to use all th predefined features, and even use the admin settings of the default user model by doing the following in your admin.py file:

from django.contrib.auth.admin import UserAdmin as DefaultUserAdmin

@admin.register(User)
class UserAdmin(DefaultUserAdmin):
    ...

If you are starting out I hope this information was useful.

By Gonçalo Valério

Software developer and owner of this blog. More in the "about" page.