SoFunction
Updated on 2025-03-02

Detailed explanation of the AbstractUser extension of Django User module

I'm writing a blog recently and I happened to write about the user registration and cancellation module. I think this aspect is quite interesting. When trying to open the source code of Django, all APIs will not become so intangible. By reading the source code of Django's modules, we can change the code more flexibly to achieve the functions we want.

Now, let’s think about a question. The main requirement is to realize the user’s registration, login and logout function in the blog. If you are only satisfied with registering the user's email or username when registering, the User module that comes with Django can be implemented. But in fact, a common requirement is that registered users should be able to modify their avatar information, email information, nickname information and other more flexible needs.

You can first look at the source code of the Django User module

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():
    swappable = 'AUTH_USER_MODEL'

Note: If yours is managed by Anaconda, you can view it in the path C:\Users\User\Anaconda3\Lib\site-packages\django\contrib\auth\

The User module in Django actually inherits the AbstractUser module, and the AbstractUser module has:

username
first_name
last_name
email
date_joined

You can see that the User module inherits the AbstractUser abstract base class, but only inherits it, and does not make any extensions to AbstractUser. Therefore, for a User module information that requires more needs, we can inherit AbstractUser and expand according to our needs.

Now, we have added some requirements for user attributes, such as supporting users to modify their avatars, supporting user nicknames, qq, wechat and website links.

class User(AbstractUser):
  nickname = (max_length=30, blank=True, null=True, verbose_name='Nick name')
  qq = (max_length=20, blank=True, null=True, verbose_name='QQ number')
  url = (max_length=100, blank=True, null=True, verbose_name='Personal Web Address')
  avatar = ProcessedImageField(upload_to='avatar',
default='avatar/', verbose_name='avatar')

  class Meta:
    verbose_name = 'user'
    verbose_name_plural = verbose_name
    ordering = ['-id']

  def __str__(self):
    return 

We add nickname (nickname), qq, url (website link), and avatar (avatar) attributes to the customized user module.

Note: In order for Django to recognize user models that use customization, you must set the custom module location in , such as adding it on

AUTH_USER_MODEL = ''

Among them, blog is your corresponding application app information, and user is the user module under blog application. Here blog has nothing to do with user case.

If you execute the database migration command now, you may prompt that the user module does not exist in the blog, and the data migration cannot be re-processed.

ValueError: The field  was declared with a lazy reference to '', but app 'blog' doesn't provide model 'user'.
The field  was declared with a lazy reference to '', but app 'blog' doesn't provide model 'user'.
The field  was declared with a lazy reference to '', but app 'blog' doesn't provide model 'user'.
The field easy_comment. was declared with a lazy reference to '', but app 'blog' doesn't provide model 'user'.
The field easy_comment. was declared with a lazy reference to '', but app 'blog' doesn't provide model 'user'.
The field  was declared with a lazy reference to '', but app 'blog' doesn't provide model 'user'.
The field online_status. was declared with a lazy reference to '', but app 'blog' doesn't provide model 'user'.
The field  was declared with a lazy reference to '', but app 'blog' doesn't provide model 'user'.

So, if you used a user model like AUTH_USER_MODEL = before and redefined it as AUTH_USER_MODEL = please delete all files and database files in the migrations directory.

After deletion, re-migrate the database

$ python  makemigrations myapp
$ python  migrate

At this time, the user used is the customized user.

 File "C:\Users\Micky\Anaconda3\lib\site-packages\django\db\backends\", line 85, in _execute
  return (sql, params)
 File "C:\Users\Micky\Anaconda3\lib\site-packages\django\db\backends\sqlite3\", line 303, in execute
  return (self, query, params)
: no such table: blog_user

Here you can specify the database db_table = 'user' in the template

Supplementary knowledge: Django learning notes - built-in user class AbstractUser and built-in authentication verification system

Built-in user class AbstractUser

We have talked about the role of the model model and the role of the parent class. The built-in user class AbstractUser introduced this time is a class built-in Django about user operations. It greatly facilitates our design of the User user class in the model model. The essence of the so-called built-in user class is an encapsulated parent class, so it is quite convenient to use.

#Import AbstractUser classfrom  import AbstractUser

#Just inherit directly, if necessary, just write fields like ordinary modelsclass User(AbstractUser):
  pass

We can see how many fields it has by looking at the source code of AbstractUser

#usernameusername = (
    _('username'),
    max_length=150,
    unique=True,
    help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
    validators=[username_validator],
    error_messages={
      'unique': _("A user with that username already exists."),
    },
  )
  
  #name  first_name = (_('first name'), max_length=30, blank=True)
  
  #surname  last_name = (_('last name'), max_length=150, blank=True)
  
  #Mail  email = (_('email address'), blank=True)
  
  #Permissions  is_staff = (
    _('staff status'),
    default=False,
    help_text=_('Designates whether the user can log into this admin site.'),
  )
  
  #activation  is_active = (
    _('active'),
    default=True,
    help_text=_(
      'Designates whether this user should be treated as active. '
      'Unselect this instead of deleting accounts.'
    ),
  )
  
  #date  date_joined = (_('date joined'), default=)

Built-in authentication verification system

django's own user authentication verification system is relatively simple, mainly whether the authentication username and password are correct or not.

First, configure it in settings

#Use the built-in authentication system
AUTH_USER_MODEL = ""

This is used with the included user class AbstractUser

Usually, use the post method in class view to verify user login and other operations

The specific code in the view is as follows

class LoginView(View):

  def get(self,request):
    #Logistic Code    return render(request,'')

  def post(self,request):
    # Get the username and password passed by the front-end    username = ('username')
    pwd = ('pwd')
    record = ('record')
    # Perform data verification    if not all([username,pwd]):
      return HttpResponse('Data input is incomplete')
    # Verify that the username and password are correct    user = authenticate(username=username,password=pwd)
    return render(request,''')

The main thing is user = authenticate(username=username,password=pwd)

Both parameters are obtained from the information entered by the front-end user

The above detailed explanation of the AbstractUser extension of the Django User module is all the content I share with you. I hope you can give you a reference and I hope you can support me more.