User authentication (Auth) component
The Django user authentication (Auth) component is generally used for user login registration to determine whether the current user is legal and jump to the login success or failure page.
Django user authentication (auth) component needs to import auth module
# Authentication module from django.contrib import auth # Corresponding database from django.contrib.auth.models import User
The return value is the user object
There are three ways to create user objects:
- create(): create an ordinary user whose password is plaintext
- create_user(): create an ordinary user whose password is ciphertext
- create_superuser(): create a super user whose password is ciphertext. You need to pass an additional email parameter.
Example
from django.contrib.auth.models import User User.objects.create(username='root',password='root') # Password is clear text
from django.contrib.auth.models import User user = User.objects.create_user(username='root',password='root') # Password is ciphertext
from django.contrib.auth.models import User user = User.objects.create_superuser(username='root',password='root', email='root@root') # Superuser
Common modules
- authenticate()
To verify the user name and password, use the authenticate() method. You need auth_user objects are filtered from the user table.
Import before use
from django.contrib import auth
Return value: if the verification is successful, the user object is returned; otherwise, None is returned
example
def login(request): if request.method == "GET": return render(request, "login.html") username = request.POST.get("username") password = request.POST.get("pwd") valid_num = request.POST.get("valid_num") keep_str = request.session.get("keep_str") if keep_str.upper() == valid_num.upper(): user_obj = auth.authenticate(username=username, password=password) print(user_obj.username)
- login(HttpRequest, user)
Realize the function of user login. In essence, relevant session data will be generated for the user on the back end
example
def login(request): if request.method == "GET": return render(request, "login.html") username = request.POST.get("username") password = request.POST.get("pwd") valid_num = request.POST.get("valid_num") keep_str = request.session.get("keep_str") if keep_str.upper() == valid_num.upper(): user_obj = auth.authenticate(username=username, password=password) print(user_obj.username) if not user_obj: return redirect("/login/") else: auth.login(request, user_obj) path = request.GET.get("next") or "/index/" print(path) return redirect(path) else: return redirect("/login/")
- logout(request)
This function accepts an HttpRequest object with no return value
When this function is called, all the currently requested session information will be cleared.
example
def logout(request): ppp = auth.logout(request) print(ppp) # None return redirect("/login/")
- login_requierd()
A decorator tool provided by auth to quickly add login verification to a view
example
from django.contrib.auth.decorators import login_required @login_required def my_view(request): ...
If the user does not log in, it will jump to the default login URL of django and pass the absolute path of the current URL (after successful login, it will be redirected to this path)
If you need to customize the login URL, you need to click settings Py file via LOGIN_URL.
Example
LOGIN_URL = '/login/' # Configure the route of the project login page here
- check_password(password)
auth provides a method to check whether the password is correct. It needs to provide the password of the current requesting user.
If the password is correct, return True; otherwise, return False
Example
ok = user.check_password('password')
- set_password(password)
auth provides a method to modify the password. It accepts the new password to be set as a parameter.
Note: after setting, you need to call the save method of the user object
user.set_password(password='') user.save()
Extend default auth_user table
Customize the new Model class by inheriting the built-in AbstractUser class.
In this way, the user table can be set flexibly according to the project requirements, and the powerful authentication system of Django can be used.
from django.contrib.auth.models import AbstractUser class UserInfo(AbstractUser): """ User information table """ nid = models.AutoField(primary_key=True) phone = models.CharField(max_length=11, null=True, unique=True) def __str__(self): return self.username
Note: the built-in auth is extended_ After the user table, you need to enter the settings PY
# It refers to the User table provided by Django. It needs to be set during inheritance and use AUTH_USER_MODEL = "app name.UserProfile"