Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The basic authentication module auth of Django framework is applied like this.

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article Xiaobian for you to introduce in detail the "Django framework basic authentication module auth so application", the content is detailed, the steps are clear, the details are handled properly, I hope this "Django framework basic authentication module auth so application" article can help you solve doubts, following the editor's ideas slowly in-depth, together to learn new knowledge bar.

1. Auth introduction

Django comes with a user authentication system. It handles user accounts, groups, permissions, and cookie-based user sessions.

The authentication system consists of the following parts:

User

Permissions: binary (yes / no) identifies whether the specified user can perform specific tasks.

Groups: a general way to apply labels and permissions to multiple users.

Configurable password hashing system

Provide form and view tools for logging in users or restricting content

Pluggable back-end system

2. Autho common operations 2.1 create users

Create a user using a User object.

Create a normal user

> from django.contrib.auth.models import User > user = User.objects.create_user (username='john', email='lennon@thebeatles.com', password='johnpassword') > user.last_name = 'Lennon' > user.save () # create ordinary users without writing email

Create a superuser:

>: python manage.py createsuperuser user (leave blank to use 'hans'): test Email address: Warning: Password input may be echoed. Password: or: python manage.py createsuperuser-- username=joe-- email=joe@example.com and then enter the code to create a superuser: > from django.contrib.auth.models import User > user = User.objects.create_superuser () ('john',' lennon@thebeatles.com', 'johnpassword') > user.last_name =' Lennon' > > user.save () # to create a superuser, you must write email2.2 to authenticate the user

Use authenticate () to authenticate the user, that is, to verify that the user name and password are correct. It uses username and password as parameters for validation, and returns a: class:~django.contrib.auth.models.User object if the back-end validation is valid. If the backend throws a PermissionDenied error, it returns None.

From django.contrib.auth import authenticateuser = authenticate (username='john', password='secret') if user is not None: # A backend authenticated the credentialselse: # No backend authenticated the credentials2.3 verify whether the user is logged in

Use request.user.is_authenticated to verify that the user is logged in and always returns True (anonymous user AnonymousUser.is_authenticated always returns False). This is a way to determine whether a user has been authenticated.

If request.user.is_authenticated: # Do something for authenticated users. ... else: # Do something for anonymous users. . # No user login will be set to AnonymousUser otherwise set to login user # use in the front-end model version: {% if request.user.is_authenticated%} {{request.user.username}} Welcome {% else%} Please log in {% endif%} 2.4 authenticated users want to attach to the current session # for example, users who want to get a specific login after login. You can use login () from django.contrib.auth import loginlogin (request, user, backend=None) 2.5 to quickly add login verification decorator.

Auth provides a decorator tool that is used to quickly add login checks to a view.

From django.contrib.auth.decorators import login_required@login_required (url='/login/') # if you are not logged in, jump to the login page def my_view (request): in version # 3.2 @ login_required (login_url='/login/') 2.6 exit login from django.contrib.auth import logoutlogout (request) after calling logout (), all the session data requested will be cleared. This is to prevent other users using the same browser from accessing the session data of the previous user. If the user is not logged in, logout () will not report an error. Check password check_password (raw_password) returns True if the given original string is the correct password for the user. (password hash value is used for comparison) 2.8 modify password set_password Note: be sure to call the save method of the user object after setting! Another method: python manage.py changepassword * username*2.9. Example: use auth module to build login pages that can be accessed and have exit function

HTML Code:

Home.html: home page Title

{{user}}, welcome to login

Log out of the login.html # login page Title user login {% csrf_token%} username: Password: registered user register.html # Registration Page Title {% csrf_token%} Username: password: Confirm Password: email: logout.html # exit page Title

{{user}} exited

Views.py code

From django.shortcuts import render,HttpResponse, redirect# Create your views here.from django.contrib.auth.models import Userfrom django.contrib.auth import authenticate,login, logoutfrom django.contrib.auth.decorators import login_requireddef auth_login (request): # login function if request.method = = "POST": username= request.POST.get ("username") password = request.POST.get ("password") print (username, password) user = authenticate (username=username) Password=password) # verify that the user password is correct if user is not None: print ("login successful") login (request, user) # authenticated users attach to the current session return redirect ("/ home/") else: return HttpResponse ("wrong username or password") return render (request "login.html") @ login_required (login_url='/login/') # if you are not logged in, use login_required to jump to the login page def home (request): # Home if request.user.is_authenticated: return render (request, "home.html", {"user": request.user}) else: return render (request "home.html") def register (request): # Registration if request.method = = "POST": username= request.POST.get ("username") password= request.POST.get ("password") email= request.POST.get ("email") print (username,password, email) user = User.objects.create_user (username=username,password=password,email=email) user.save () return render (request "register.html") def auth_logout (request): # exit user = request.user logout (request) return render (request, "logout.html", locals ())

Urls.py code

From django.contrib import adminfrom django.urls import pathfrom auth01 import viewsurlpatterns = [path ('admin/', admin.site.urls), path (', views.home), path ('home/', views.home), path (' login/', views.auth_login), path ('register/', views.register), path (' logout/', views.auth_logout),]

Visit: http://127.0.0.1:8000/home

Enter user and password: test/123

Click to exit

2.10 is_staff and is_activeis_staff of the User object: whether the user has administrative rights to the site. If not, the backend admin login does not enter is_active: whether to allow users to log in, set to False, you can prohibit users from logging in without deleting users. 3. Extend the default auth_ user table 3.1 scenario 1: one-to-one extension from django.contrib.auth.models import User class user_info (models.Model): user=models.OneToOneField (to=User) phone=models.CharField (max_length=32) # adds phone fields 3.2 scenario 2: inherits the AbstractUser class extension if the auth_user table is not created before the operation 1. Write a class that inherits AbstractUser 2. 0. Expand the field in the class (you can rewrite the original field) class MyAuthUser (AbstractUser): phone=models.CharField (max_length=32) 3. Configure # in the configuration file (settings.py) to refer to the User table that comes with Django. You need to set AUTH_USER_MODEL = "APP name when inheritance is used. Self-created table name "such as: AUTH_USER_MODEL =" auth01.MyAuthUser "# if you already have an auth_ user table, you need the following three steps to expand and write:-delete the library-clear all the migration records in the project-empty the migration records of both admin,auth and app in the source code. This is the end of the article" how to apply auth to the basic authentication module of the Django framework ". If you want to master the knowledge of this article, you still need to practice and use it. If you want to know more about the articles, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report