django user authentication component auth

brief introduction

django provides a very useful component which is responsible for the full set of functions of user login authentication, which is the auth component.

With the auth component, we no longer need to manually write the login check decorator, nor set session s manually to save user state.

The django project executes the database migration command and generates a set of default tables, including auth_The user table, auth components, and this table are closely related.

In addition, django projects will have an admin backend management system by default, and the logged-in user information is saved in auth_user table; and users are divided into normal and super users, only super users can log in to admin background management system.

# Create a superuser from the command line
python3 createsuperuser

Basic use of auth module

common method

Logon verification:auth.authenticate()

user_obj = auth.authenticate(request,


# Note:
    1.authenticate()User name and password must be passed in parentheses at the same time
    2.Password Automatic Encryption Check
    3.Check succeeds, returns the current object, and fails None

Save user status:auth.login()

auth.login(request, user_obj)  

# Note:
    1.This method requires request,Two methods with the currently logged-in user object
    2.This method is set automatically session,Be similar to request.session[key] = user_obj
    3.Once this method is executed, it can be passed anywhere request.user Get the currently logged on user object

Get the current logged-on user object


Determine whether the current user is logged on:


Login Decorator

from django.contrib.auth.decorators import login_required

def index(request):

# Note:
    1.Pages jumped to when not logged in require manual settings; settings are divided into local settings and global settings.
    2.Local settings, passing parameters directly inside the decorator login_url Appoint
    3.Global settings, through parameters in the configuration file LOGIN_URL = '/login/'Set up
    4.Decorators help us after jumping url Added after target_url,We are in login Capture it manually in a view function
    4.Priority of Local Settings and Global Settings
    #5. The global benefit is that there is no need to repeat the code, but the page you jump to is very simple
    #6. The local advantage is that different view functions can jump to different pages without users logging in

Verify that the password is correct:


Change Password:


    Two are required, the first step is only to modify the properties of the object; the second step is to actually manipulate the database


auth.logout(request) 		# Equal toRequest.session.flush()


# Mode 1: Operate auth_user table writes data (not recommended, password is not encrypted)
from django.contrib.auth.models import User
User.objects.create(username=username, password=password) 

# Mode 2: Create a regular user
User.objects.create_user(username=username, password=password)

# Mode 3: Create Super User

#Be careful:
	1.Return current object after successful creation of mode 2 and mode 3
	2.Use code to create superuser, mailbox is required, and command to create can not


auth.authenticate()			# Verify logon user name and password
auth.login(request, user_obj) 		# Save login status after login
auth.logout(request)			# Cancellation

# Once you have saved your login status, you can go through it anywhereRequest.userGet the currently logged on user object
# Once you get the current object, you can get object properties and methods by point

request.user.is_authenticated()		# Determine whether an object is logged on
request.user.check_password()		# Check to see if the user's password is correct

request.user.set_password()			# Set password (update password)				# Password must be save d before it is valid

# Other methods
User.objects.create_user()			# Create Ordinary User
login_required					# Login Verification Decoration

# Summary: Use the full suite with auth
    //Advantages: Encapsulates a large number of built-in methods for ease of use
    //Disadvantages: high coupling, full use only, poor flexibility

Extended auth_user table

Using the auth component's functionality requires additional new fields

Solution 1 (not recommended)

Create a new user table and auth_using foreign key constraints on tables and tablesUser table one-to-one foreign key association.

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

class UserDetail(models.Model):
     phone = models.BigIntegerField()
     user = models.OneToOneField(to='User')

Solution 2 (Recommended)

Using the class inheritance relationship, define a new class to inherit AbstractUser, adding several new attributes

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

class UserInfo(AbstractUser):
    phone = models.BigIntegerField()

Benefits of Mode 2

  • Write your own table UserInfo that inherits AbstractUser, auth_when executing database migration commandsThe user table is no longer created
  • Auh_appears in the UserInfo tableUser All Fields plus Self Extended Fields
  • The advantage of this is that you can click directly on your own table to complete operations and expand faster
  • Write your own table UserInfo instead of auth_user, then the auth module functions as usual, referencing the table page from the original auth_user becomes UserInfo

Prerequisites for Mode 2

  • No database migration command was executed before inheritance; that is, if auth_already existsThe user table cannot use this method.

  • Do not override field names in AbstractUser in inherited classes; do not move any fields in the table; just extend additional fields.

  • You need to tell django in the configuration file that you want to use UserInfo instead of auth_user

    # collocation method
    AUTH_USER_MODEL = 'app01.UserInfo'		# 'Application name. Table name'

Keywords: Django Session Database

Added by oughost on Wed, 10 Jun 2020 04:51:49 +0300