djangodjango-users

Django - Why should I extend User as opposed to creating my one user class


All,

I'm having some difficulty understanding what is the advantage of extending the user class in Django? I feel it's more advantageous to overwrite it and create my own user class, with all the files that I want.

I'm asking this because all the tutorials that I see always refer to create a profile class and from there extend the user class.

I would see the advantage if I wanted to extend the user class multiple times, but I feel that this never happens.


Solution

  • You need to extend the AbstractUser class because you will want to use the functionality that django has already provided. This includes authentication, group, permissions, etc.

    You will not want to write all from scratch. Even if you plan to write all on your own because of unique needs of your application, it is still advisable to extend the AbstractUser class. May be you will need to use some of its feature in future.

    Contrary to your case, if someone needs only functionality of User model already provided by Django, it is still advisable to create new model that extends AbstractUser class. This is because, once you have set AUTH_USER_MODEL in your settings.py, you can't change it (or will be very difficult) to change in future. Doing this, will always give you freedom to use all the functionality that django has provided and implement the functionality you may need to implement.

    So, the ideal thing is to always do this in the beginning of any project (before any migrations):

    users.py

    from django.contrib.auth.models import AbstractUser
    
    class User(AbstractUser):
        
        phone = models.CharField(max_length=25, blank=True,unique=True, null=True)
    
        def __str__(self):
            return self.username
    
    

    And in your settings.py.

    AUTH_USER_MODEL = 'users.User'