Django's auth module (user authentication) login component

Introduction to the auth module

The auth module is an encapsulation of the login authentication method. Before we obtained the user name and password entered by the user, we needed to query the user table for objects that match the user name and password.

With the auth module, it is easy to verify whether the user's login information exists in the database.

In addition, auth also encapsulates the session, which is convenient for us to verify whether the user is logged in


method in auth

If you want to use the methods of the auth module, you must first import the auth module

from django.contrib import auth

1 ,authenticate()   

Provides user authentication, that is, to verify whether the user name and password are correct, generally requires two keyword parameters of username and password

If the authentication information is valid, a User object is returned. authenticate() will set an attribute on the User object to identify which authentication backend authenticated the user, and this information is required in the subsequent login process. When we try to log in to a User object that is directly retrieved from the database without authenticate(), an error will be reported! !

user = authenticate(username='someone',password='somepassword')


2 ,login(HttpRequest, user) 

This function accepts an HttpRequest object, and an authenticated User object

This function uses django's session framework to attach information such as session id to an authenticated user.

from django.contrib.auth import authenticate, login
def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        login(request, user)
        # Redirect to a success page.
        # Return an 'invalid login' error message.


3. logout(request) to log out the user

This function accepts an HttpRequest object and returns no value. When this function is called, the session information of the current request will be cleared. Even if the user is not logged in, using this function will not report an error.

from django.contrib.auth import logout
def logout_view(request):
  # Redirect to a success page.


4. is_authenticated() of the user object


1 Users can only access certain pages after logging in,

2 If the user visits the page without logging in, jump directly to the login page

3 After the user completes the login in the jumped login interface, the user will automatically access and jump to the previously visited address

method 1:

Authenticate directly with the is_authenticated() method of auth

def my_view(request):
      if not request.user.is_authenticated():
            return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))

Method 2:

Verify according to request.user.username, if it is empty, it means no login

def my_view(request):
      if not request.user.username:
            return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))

Method 3:

django has designed a decorator for us in this case: login_requierd()

from django.contrib.auth.decorators import login_required
def my_view(request):

If the user is not logged in, it will jump to the default django login URL '/accounts/login/ ' (this value can be modified in the settings file through LOGIN_URL). And pass the absolute path of the current access url (after successful login, it will be redirected to this path).


user object

User object attributes: username, password (required) password is saved to the database with a hash algorithm

is_staff : Whether the user has administrative rights to the site.

is_active : Whether to allow the user to log in, set to ``False``, you can prohibit the user from logging in without deleting the user

2.1 ,is_authenticated()

If it is a real User object, the return value is always True . Used to check whether the user has been authenticated.
Authenticating does not mean that the user has any permissions, nor even checking if the user is active, it just means that the user has successfully authenticated. This method is very important. In the background, use request.user.is_authenticated() to determine whether the user is logged in. If true, can be displayed to the foreground

2.2 , create a user

Use the create_user helper function to create a user:

from django.contrib.auth.models import User
user = User.objects.create_user(username='',password='',email='')

2.3 ,check_password(passwd)

user = User.objects.get(username=' ')
if user.check_password(passwd):

When the user needs to change the password, first let him enter the original password, if the given string passes the password check, return True

Use set_password() to change the password

user = User.objects.get(username='')

2.5, simple example


def sign_up(request):
    state = None
    if request.method == 'POST':
        password = request.POST.get('password', '')
        repeat_password = request.POST.get('repeat_password', '')
        email=request.POST.get('email', '')
        username = request.POST.get('username', '')
        if User.objects.filter(username=username):
                state = 'user_exist'
                new_user = User.objects.create_user(username=username, password=password,email=email)
                return redirect('/book/')
    content = {
        'state': state,
        'user': None,
    return render(request, 'sign_up.html', content) 


change Password:

def set_password(request):
    user = request.user
    state = None
    if request.method == 'POST':
        old_password = request.POST.get('old_password', '')
        new_password = request.POST.get('new_password', '')
        repeat_password = request.POST.get('repeat_password', '')
        if user.check_password(old_password):
            if not new_password:
                state = 'empty'
            elif new_password != repeat_password:
                state = 'repeat_error'
                return redirect("/log_in/")
            state = 'password_error'
    content = {
        'user': user,
        'state': state,
    return render(request, 'set_password.html', content)


Create the User table yourself

It should be noted that all the above operations are for the auth_user table automatically created by django, we can take a look at the structure of this table



This is a user table that django automatically created for us, and if you want to use the auth module, you must use (or inherit) this table.

The advantage of inheriting the table is that we can add some fields we need, and at the same time we can use the interfaces and methods provided by the auth module

Let's talk about the method of inheriting auth:

1. Import the AbstractUser class, and write a custom class that inherits the AbstractUser class, as follows:

from django.contrib.auth.models import AbstractUser
class UserInfo(AbstractUser):
    User Info
    nid = models.AutoField(primary_key=True)
    telephone = models.CharField(max_length=11, null=True, unique=True)


It should be noted that the UserInfo table does not need to have repeated fields in auth_user, such as username and password, but these fields can still be used directly, and django will automatically encrypt the password

2. After writing this, you need to configure it in the file:

AUTH_USER_MODEL = 'blog.UserInfo'

In this way, django knows to find the UserInfo table from the models under the blog project


Posted by jaysmyhero on Mon, 30 May 2022 04:59:05 +0530