Using AbstractBaseUser In Django

Using AbstractBaseUser In Django

How to create an abstract base user class to use in a one-to-one relationship with another class

Introduction

If you are like me, you have probably worked your way through the Django documentation and probably haven’t understood this yet.

Well, I just cracked this huge case, and it was an ordeal.

AbstractBaseUser is a model class in Django, and much like AbstractUser, which is a subclass of AbstractBaseUser, it inherits from the default User Model in Django. Like its sibling, it is an abstraction of the User Model, but unlike it and the aforementioned, it allows for almost complete control over the fields of models.

AbstractBaseUser has authentication functionalities only and contains just three fields, which include:

  • id

  • last_login

  • password

That means you will need to put in the other fields.

When to use which?

Well, this is not easy to answer. It depends on what you want to achieve and what suits your project best. If you don’t want to have much control over what happens, I say use the User Models, if you want to have the user fields, but with additional fields, you can use the Abstractuser class, if you want to have control over what stays or not in the user table, then you can go ahead with AbstractBaseUser.

This article concentrates on how to use AbstractBaseUser.

How To Use AbstractBaseUser To Create User Fields

This is how to use AbstractBaseUser to create a user table for all users that visit a website:

  • Import models from django.db

from django.db import models

  • Import AbstractBaseUser, PermissionMixins

  • Create a class, with a clear descriptive name

  • Create the fields you wish to include in the user table.

  • Check your code for any mistakes or blunders.

  • Run migrations using python manage.py makemigrations

  • Migrate using ‘python manage.py migrate`. If your terminal does not run with python, use py instead.

Establishing One-To-One Relationship

To establish the One-To-One relationship between the user table and the user profile table:

  • Create another class in the same models.py file.

  • Create fields you want each user to have.

  • Instantiate the previous class as a model field type. Like so;

  • Finally, run migrations again

  • Migrate

This is how you can properly use AbstractBaseUser. This method can be used with AbstractUser as well but not with the User model. To create a One-To-One relationship using the User Model, just go right ahead and instantiate it in the class Profile. You don’t need to create an Abstract user class. Read the documentation for more understanding of the use of model classes.

I hope this helped. If I used outdated information or you have another way of doing this, please let me know in the comments.

Thank you for reading!