# 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
Official website reference address :https://docs.djangoproject.com/zh-hans/3.2/topics/auth/default/#user-objects
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")
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")
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' """
>>> 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 ")
u = User.objects.get(username='aa')
u.check_password('my password')
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>
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 .
Same as before , use django With login status verification decorator , Verify the login status . Which view needs , Just before which view .
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
...
from django.contrib.auth import logout
def logout(request):
logout(request)
# Request to come , And then session Empty , To cancel login
# 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
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")
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")
def logout(request):
logout(request)
return HttpResponseRedirect("/login")
# 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")
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 .
User
Model class 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
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="")
settings.py
Named in the AUTH_USER_MODDEL=" Application name . Class name "
# The position of mysite_name/settings.py
AUTH_USER_MODEL = 'appname.UserInfo'
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")