Django User Authentication System: Extending User Model

Source: Internet
Author: User
Keywords django user django user model how to extend django user model
The Django user authentication system provides a built-in User object, which is used to record the user's user name, password and other personal information. For Django's built-in User model, it only contains the following main attributes:
  • username, which is the username
  • password
  • email, mailbox
  • first_name, first name
  • last_name, last name

Alibaba Cloud Simple Application Server:  Anti COVID-19 SME Enablement Program
$300 coupon package for all new SMEs and a $500 coupon for paying customers.

For some websites, users may also include other attributes such as nicknames, avatars, personal signatures, etc., so just using Django's built-in User model is not enough. Fortunately, the Django user system follows the extensible design principle, and we can easily extend the User model.

Inherit AbstractUser to extend user model

This is the recommended practice. In fact, if you look at the source code of the User model, you know that User also inherits from the AbstractUser abstract base class, and only inherits AbstractUser, without any extension to AbstractUser. The following is the source code of User:

class User(AbstractUser):
    """
    Users within the Django authentication system are represented by this
    model.

    Username, password and email are required. Other fields are optional.
    """
    class Meta(AbstractUser.Meta):
        swappable ='AUTH_USER_MODEL'

So, if we inherit AbstractUser, we will get all the features of User, and we can also expand it according to our needs.

We created a users application before, usually we write the code related to the database model in the models.py file. Open the users/models.py file and write our custom user model code:
users/models.py

from django.db import models
from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
    nickname = models.CharField(max_length=50, blank=True)

    class Meta(AbstractUser.Meta):
        pass
 We have added a nickname attribute to the custom user model, which is used to record the user's nickname information. The purpose of setting blank=True is to prevent users from filling in the nickname when registering. You can further expand it according to your needs, such as adding user avatars, personalized signatures, etc. There is no limit to how many attribute fields you can add.
At the same time, we inherited the internal class attribute Meta of AbstractUser, but we haven't done anything yet. The reason for inheriting Meta here is that you may need to set some attribute values of the Meta class in your project. Don't forget to inherit the existing attributes in AbstractUser.Meta.

Note: Be sure to inherit AbstractUser, not auth.User. Although auth.User inherits from AbstractUser without any additional extensions to it, AbstractUser is an abstract class, and auth.User is not. If you inherit the auth.User class, this will become multi-table inheritance, which is not recommended in the current situation. For Django's abstract model classes and multi-table inheritance, please refer to Django's official document Model Inheritance.

In addition, the AbstractUser class inherits from AbstractBaseUser, the former expands a set of user permissions (Permission) system on the latter. Therefore, if there is no special need, try not to extend from AbstractBaseUser, otherwise you need to do more extra work.
In order for the Django user authentication system to use our custom user model, the location of the custom user model must be specified through AUTH_USER_MODEL in settings.py, which requires the following settings:
django_auth_example/settings.py

# Other settings...
AUTH_USER_MODEL ='users.User' copying the code tells Django to use the User user model under the users application.

By the way, modify the language settings and time zone settings:

django_auth_example/settings.py

# Other settings...

LANGUAGE_CODE ='zh-hans'
TIME_ZONE ='Asia/Shanghai' 

After setting up a custom user model, generate a database migration file, and migrate the database to generate the necessary database tables for each application. That is, run the following two commands:

$ python manage.py makemigrations
$ python manage.py migrate 

OK, now the user model used by the Django user system is the custom User model.

Note: After setting AUTH_USER_MODEL ='users.User', you must migrate the database for the first time, that is, specify a custom user model before executing the database migration command.

Use Profile mode to extend the user model

If you want to expand the user model for a project that already uses Django's built-in User model, the above extension method of inheriting AbstractUser will become a bit troublesome. Django does not provide an automated way to migrate the built-in User to a custom user model, because Django has already generated related database migration files and database tables for the built-in User model. If you have to do this, you need to manually modify the migration files and database tables, and move the related user data in the database.
So we use another way to expand the user model without changing the database table. Specifically, we are creating a model (usually named Profile) to record user-related data, and then use a one-to-one approach to the Profile model Associating with User is as if each user is associated with a table that records personal information. code show as below:

models.py

from django.contrib.auth.models import User

class Profile(models.Model):
    nickname = models.CharField(max_length=50, blank=True)
    user = models.OneToOneField(User) 

The difference between this method and AbstractUser is that the user model that inherits AbstractUser has only one database table. The Profile model has two tables, one is the table corresponding to the User model, the other is the table corresponding to the Profile model, and the two tables are related through a one-to-one relationship. It can be seen that when you want to query a user's Profile, you need to perform additional cross-table query operations, so this method is a bit less efficient than directly inheriting AbstractUser. Therefore, for new projects, it is recommended to extend the user model by inheriting AbstractUser.

PS: If you use the Profile mode, you may want to create the Profile object associated with it when creating the User object. You can use Django's Signal to achieve this requirement. Since the Profile mode is not the focus of our introduction, please refer to the relevant documents for specific implementation details, and I won’t repeat them here.

OK, the custom User model has been established, the next step is how to create users, that is, the user registration process.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.