[Django Development Manual] Using a custom user model in Django: a stronger choice than the built-in User

Foreword

Django is a very popular Python web framework. Its built-in user authentication system can help us easily implement functions such as registration, login, and permission control. However, if you need to implement more functions, such as custom user attributes, or implement different user types (such as ordinary users and administrator users, etc.), using Django’s own User model may become more cumbersome and limited. At this time, custom user models become a good solution.

This blog will introduce how to create a custom user model in Django and give a complete code example.

Get started quickly

Before implementing a custom user model, you need to pay attention to the following issues:

  • Django’s own user management views and templates use User to create tables. If you need to customize the user model, you need to point the AUTH_USER_MODEL configuration item to the new model in the project’s settings.py file. In this way, all properties and methods of our custom user model can be used.
  • The custom user model needs to inherit the AbstractBaseUser and PermissionsMixin models. The AbstractBaseUser model defines the most basic user information (user name and password), and the PermissionsMixin model is mainly used to manage permissions.
  • Customizing the user model requires defining a Manager class for managing and operating the database. Implement methods such as create_user and create_superuser in the Manager class to create ordinary users and administrator users.
  • A custom user model needs to define an Admin class to manage the background management page, including fieldsets, list_display, list_filter, search_fields and other related attributes and methods.

Here is sample code for a complete custom user model:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin

class MyUserManager(BaseUserManager):
    def _create_user(self, email, password=None, **extra_fields):
        if not email:
            raise ValueError('The Email field must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        return self._create_user(email, password, **extra_fields)

class MyUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    is_staff = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = []

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return self.is_superuser

    def has_module_perms(self, app_label):
        return self.is_superuser

    @property
    def is_admin(self):
        return self.is_superuser

    @property
    def is_staff(self):
        return self.is_admin
    
class MyUserAdmin(UserAdmin):
    add_form_template = 'admin/auth/user/add_form.html'
    fieldsets = (
        (None, {'fields': ('email', 'password', 'is_staff')}),
        (_('Permissions'), {
            'fields': ('is_active', 'is_superuser'),
            'description': _('Designates whether this user should be treated as '
                             'active, and whether they have all permissions.')
        }),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'password1', 'password2'),
        }),
    )
    list_display = ('email', 'is_staff')
    list_filter = ('email', 'is_staff', 'is_superuser', 'is_active', 'groups')
    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ('groups', 'user_permissions',)
    
admin.site.register(MyUser, MyUserAdmin)

In the code, we customized a MyUser model, which inherits the AbstractBaseUser and PermissionsMixin models, contains two fields: email and is_staff, and defines the MyUserManager class to operate the database and the MyUserAdmin class to manage the background management page.

In the settings.py file, we need to point the AUTH_USER_MODEL configuration item to this MyUser model:

AUTH_USER_MODEL = 'myapp.MyUser'

The function of this setting is to replace Django’s default user model with our own defined MyUser model, so that all properties and methods of the user model we defined can be used in our project.

Conclusion

Using a custom user model is a great way to implement some advanced user management and permission control in a Django project. Before using a custom user model, you need to read Django’s official documentation and implement it according to the above method.


———————————END——————- ——–

Digression

In the current era of big data, how can one keep up with the times without mastering a programming language? Python, the hottest programming language at the moment, has a bright future! If you also want to keep up with the times and improve yourself, please take a look.

Interested friends will receive a complete set of Python learning materials, including interview questions, resume information, etc. See below for details.


CSDN gift package:The most complete “Python learning materials” on the Internet are given away for free! (Safe link, click with confidence)

1. Python learning routes in all directions

The technical points in all directions of Python have been compiled to form a summary of knowledge points in various fields. Its usefulness is that you can find corresponding learning resources according to the following knowledge points to ensure that you learn more comprehensively.

img
img

2. Python essential development tools

The tools have been organized for you, and you can get started directly after installation! img

3. Latest Python study notes

When I learn a certain basic and have my own understanding ability, I will read some books or handwritten notes compiled by my seniors. These notes record their understanding of some technical points in detail. These understandings are relatively unique and can be learned. to a different way of thinking.

img

4. Python video collection

Watch a comprehensive zero-based learning video. Watching videos is the fastest and most effective way to learn. It is easy to get started by following the teacher’s ideas in the video, from basic to in-depth.

img

5. Practical cases

What you learn on paper is ultimately shallow. You must learn to type along with the video and practice it in order to apply what you have learned into practice. At this time, you can learn from some practical cases.

img

6. Interview Guide

Resume template

CSDN gift package:The most complete “Python learning materials” on the Internet are given away for free! (Safe link, click with confidence)

If there is any infringement, please contact us for deletion.