程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Django auth login authentication

編輯:Python

One 、Auth Module introduction

  • The user model : User authentication 、 Sign in 、 Quit and so on
  • Background management : User management 、 Permission assignment
  • Django Comes with a user authentication system , Used to process account 、 Group 、 Permission and based on Cookie User session for

1.1 Installation and configuration

# Usually comes with it 
# INSTALLED_APPS Install application 
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
# MIDDLEWARE Middleware configuration 
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
# Database migration command 
# Execute by yourself on the command line :
python manage.py makemigrations
python manage.py migrate

1.2 Auth The user types

  • Registered users (User), The super user , Ordinary users
  • tourists (AnonymousUser)

1.3 Auth Meaning of common fields

Serial number Field explain 1username user name 2password The login password 3email mailbox 4first_name name 5last_name surname 6is_superuser Is it a super administrator account /admin7is_staff Can I visit admin Management backstage 8is_active Is it an active user , The default is True, Generally, it is not deleted , Instead, it will use the user's is_active Set to False9is_authenticated Read only attribute of whether the user has logged in 10is_anonymous Whether the user logs in to the invalid read-only attribute 11date_joined User creation time 12last_login Last login time 13groups User group many to many relationship 14user_permission User authority many to many relationship

Two 、Auth User information management

Official website reference address :https://docs.djangoproject.com/zh-hans/3.2/topics/auth/default/#user-objects

2.1 Create user

  • Create a normal user
from django.contrib.auth.models import User
# Only usename Are mandatory , Don't fill in the rest 
# Create ordinary users with clear text passwords 
User.objects.create(username="AA",password="123")
# Create password as pass Django Internal automatic encryption password for ordinary users 
User.objects.create_user(username="AA",password="123")
  • Create a superuser
from django.contrib.auth.models import User
# Only usename Are mandatory , Don't fill in the rest 
User.objects.create_superuser(username="AA",password="123")

2.2 Delete user

It is recommended to use : Pseudo delete , the is_active It is amended as follows False

from django.contrib.auth.models import User
try:
user = User.objects.get(username = " user name ")
user.is_ active = False
user.save()
print(" Delete user succeeded ")
except:
print(" Failed to delete user , Or the user does not exist ")

Be careful : Unavailable update To update ,User Out-of-service .

user = User.objects.get(username = " user name ")
user.update(is_active=True)
""" Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'User' object has no attribute 'update' """

2.3 Password management

  • Change Password
>>> from django.contrib.auth.models import User
>>> u = User.objects.get(username='john')
>>> u.set_password('new password')
>>> u.save()
from django.contrib.auth.models import User
try:
user = User.objects.get(username=" user name ")
user.set_password(" Plaintext password ")
user.save()
return HttpResponse(" Password changed successfully ")
except:
return HttpResponse(" Failed to change password ")
  • Verify that the password is correct
u = User.objects.get(username='aa')
u.check_password('my password')

3、 ... and 、Auth Login verification

3.1 authenticate Login verification

from django.contrib.auth import authenticate
user = authenticate(username = username,password=password)

explain : If the user name and password are verified successfully, the corresponding user object , Otherwise return to None.

from django.contrib.auth import authenticate
user = authenticate(username="AA",password="123")
# Output correctly 
user
<User: AA>

3.2 Auth Login status remains

from django.contrib.auth import login
from django.contrib.auth import authenticate
def login_view(request):
...
# Check first 
user = authenticate(username=" user name ",password=" password ")
...
# If the verification is successful, the login status will be maintained 
login(request,user) # If the user passes the inspection , You can call this to maintain the login status 

notes : The way of preservation is session, And the time cannot be controlled , When session When does it expire , Then when to disconnect .

3.3 Auth Login status verification

Same as before , use django With login status verification decorator , Verify the login status . Which view needs , Just before which view .

  • If you are not logged in, you need to jump to the address , Need to be in settings.LOGIN_URL Set in
import django.contrib.auth.decorators import login_required
@login_required # Log in and return to the following view , Otherwise, go to the login page 
def index_view(request):
# This view can only be accessed when the user is logged in 
# The current logged in user passes request.user obtain 
login_user = request.user
...

3.3 Auth Login status cancelled

from django.contrib.auth import logout
def logout(request):
logout(request)
# Request to come , And then session Empty , To cancel login 

Four 、 be based on Auth Realize login and registration

  • Referenced related libraries
# The user model 
from django.contrib.auth.models import User
# Decorator for login status verification 
from django.contrib.auth.decorators import login_required
# Log in status 、 Exit login status 、 Verification of login user information 
from django.contrib.auth import login,logout,authenticate
  • register
def reg_view(request):
# register 
if request.method == "GET":
return render(request,"reg_view")
elif request.method == 'POST':
username = request.POST.get("user")
pwd1 = request.POST.get("pwd1")
pwd2 = request.POST.get("pwd2")
if not User.objects.filter(uesename=username):
if pwd1 == pwd2:
# Here you can. try once , Because the user name is unique , There may be SQL Uniqueness exception error 
user = User.objects.create_user(username=username,password=pwd1)
else:
return HttpResponse(" Password inconsistency , Please re-enter ")
else:
return HttpResponse(" The user name is registered , Please re-enter ")
# # Login free after user registration 
# login(request,user)
# return HttpResponseRedirect("/index")
return HttpResponseRedirect("/login")
  • Sign in
def login(request):
if request.method == "GET":
return render(request,"login.html")
elif request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
user = authenticate(username=username,password=password)
if not user:
# Wrong user name or password 
return HttpResponse(" Wrong user name or password ")
else:
# Check success 
# Record session login status 
login(request,user)
return HttpResponseRedirect("/index")
  • sign out
def logout(request):
logout(request)
return HttpResponseRedirect("/login")
  • home page
# Pages that require login status verification to access 
@login_required()
def index_view(request):
# home page , You have to log in to access , Log in and jump to settings.LOGIN_URL Set up 
# Get the current login user name 
user = request.user
return render(request,"index.html")

5、 ... and 、 Expand Django The user model in

When we want to use fields such as mobile number , Found insufficient user fields , At this time, we need to find a way to add fields .

  • programme 1: By creating a new table , Do one-on-one verification with the built-in table
    • It is troublesome to query when applying
  • programme 2: Inherit the built-in abstraction User Model class
    • Inherit the existing model fields to a new table , Tell our watch Django The original User Replace the model class with SelfUser Model class

Inherit built-in abstract classes : Solution to the problem of background management password modification

  • step1: Add new apps
  • step2: Define model classes , Inherit AbstractUser
# The position of :appname/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class UserInfo(AbstractUser):
# On the basis of the original , Add a mobile number field 
phone = models.CharField(max_length=11,default="")
  • step3:settings.py Named in the AUTH_USER_MODDEL=" Application name . Class name "
# The position of mysite_name/settings.py
AUTH_USER_MODEL = 'appname.UserInfo'
  • step4: Best in For the first time Execute the database migration command .

Be careful : This process is best done at the first migrate When the , Otherwise, use the scheme 1 appropriate . When you call the model class later, it should be UserInfo This model class .

– Add new user –

from user.models import UserInfo
user = UserInfo(username="XX",password="xxxx",phone="xxxxxxxx")

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved