This is the 19th day of my participation in the August More Text Challenge

In Django, there are two ways to customize the user model:

  • Inheritance AbstractUser
  • Inheritance AbstractBaseUser

Note: If the default authentication backend is used, the user model must have a single unique field that can be used for authentication. It can be a username, E-mail address, or any other unique attribute. If you want to use non-unique fields, you need a custom authentication back end that supports this functionality.

  • DjangoFor new projects, it is best to customizeUserModel, even thoughBuilt-in User modelThe function meets the demand. The following model and defaultUserThe model behaves exactly the same, but it can be customized in the future if new requirements arise.
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass
Copy the code
  • Also create or apply migration files for the first timebefore, you also need toPoint AUTH_USER_MODEL to the custom user model.
  • Finally, in the application ofadmin.pyRegister custom user model in file:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User

admin.site.register(User, UserAdmin)
Copy the code

Inherit AbstractUser to customize user model examples

  • inmodels.py 中Customize the user modelAs well asCustom user model manager
from django.contrib.auth.models import AbstractUser, BaseUserManager class UserManager(BaseUserManager): Def _create_user(self, telephone, username, password, **kwargs): if not telephone: raise ValueError(' ' ') if not password: raise ValueError(' Must fill in the password! ') user = self.model(telephone=telephone, username=username, **kwargs) user.set_password(password) user.save() return user def create_user(self, telephone, username, password, **kwargs): kwargs['is_superuser'] = False return self._create_user(telephone=telephone, username=username, password=password, **kwargs) def create_superuser(self, telephone, username, password, **kwargs): kwargs['is_superuser'] = True return self._create_user(telephone=telephone, username=username, password=password, **kwargs) class User(AbstractUser): telephone = models.CharField(max_length=11, unique=True) school = models.CharField(max_length=100) USERNAME_FIELD = 'telephone' REQUIRED_FIELDS = [] objects = UserManager()Copy the code
  • Configure the AUTH_USER_MODEL in settings.py
AUTH_USER_MODEL = 'front.User'
Copy the code
  • inviews.pyTo create and authenticate users
Def inherit_AbstractUser1(request) def inherit_AbstractUser1(request) telephone = '17788889999' username = 'tuanzi' password = '123456' user = User.objects.create_user(telephone=telephone, Username =username, password=password) print(user.username) return HttpResponse(' Def inherit_AbstractUser2(request) def inherit_AbstractUser2(request) telephone = '17799998888' username = 'super_tuanzi' password = '123456' user = User.objects.create_superuser(telephone=telephone, username=username, Password =password) print(user.username) return HttpResponse('Django Def inherit_AbstractUser3(request) user = authenticate(request, username='17799998888', password='123456') if user: Print (' validate successfully ') print(user.username) else: print(' validate failed ') return HttpResponse(' Validate successfully ')Copy the code

In Django, the simplest way to construct a compatible custom user model is to extend the AbstractBaseUser abstract base class.

We need to provide some key implementation details:

  • USERNAME_FIELD
  • EMAIL_FIELD
  • REQUIRED_FIELDS
  • is_active
  • get_full_name()
  • get_short_name()

In addition, the following properties and methods are available in any subclass of AbstractBaseUser:

  • get_username()
  • clean()
  • classmethod get_email_field_name()
  • classmethod normalize_username(username)
  • is_authenticated
  • is_anonymous
  • set_password(raw_password)
  • check_password(raw_password)
  • set_unusable_password()
  • has_usable_password()
  • get_session_auth_hash()

Inherit AbstractBaseUser to customize the user model example

  • inmodels.py 中Custom model manager,Customize the user model.
from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager, PermissionsMixin) from django.db import models from shortuuidfield import ShortUUIDField class UserManager(BaseUserManager): def _create_user(self, telephone, username, password, **kwargs): if not telephone: Raise ValueError(' Please pass in the phone number! ') if not username: raise ValueError(' Please pass the username! ') if not password: raise ValueError(' Please pass a password! ') user = self.model(telephone=telephone, username=username, **kwargs) user.set_password(password) user.save() return user def create_user(self, telephone, username, password, **kwargs): kwargs['is_superuser'] = False return self._create_user(telephone, username, password, **kwargs) def create_superuser(self, telephone, username, password, **kwargs): kwargs['is_superuser'] = True kwargs['is_staff'] = True return self._create_user(telephone, username, password, **kwargs) class User(AbstractBaseUser, PermissionsMixin): uid = ShortUUIDField(primary_key=True) telephone = models.CharField(max_length=11, unique=True) email = models.EmailField(unique=True, null=True) username = models.CharField(max_length=100) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'telephone' # telephone, username, password REQUIRED_FIELDS = ['username'] EMAIL_FIELD = 'email' objects = UserManager() def get_full_name(self): return self.username def get_short_name(self): return self.usernameCopy the code
  • insettings.pyIn the configurationAUTH_USER_MODELOptions. Note that you only need to add the application name to the model name and nothing else.
AUTH_USER_MODEL = 'front.User'
Copy the code
  • For the first time,Generate and run the migration file.