Knowledge Preview
User Authentication
User Authentication auth Module
from django.contrib import auth
Django. contrib. Auth provides many methods. Here we mainly introduce three of them:
1.1 authenticate ()
User authentication is provided, that is, to verify whether the user name and password are correct. Generally, two keyword parameters, username and password, are required.
If the authentication information is valid, a user object is returned. Authenticate () sets an attribute on the user object to identify the authentication backend that authenticates the user, and this information is required in the subsequent login process. When we try to log on to a user object that is directly retrieved from the database and does not pass authenticate (), an error will be reported !!
user = authenticate(username=‘someone‘,password=‘somepassword‘)
1.2 login (httprequest, user)
This function accepts an httprequest object and an authenticated user object. This function uses the Django session framework to append session ID and other information 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. ... else: # Return an ‘invalid login‘ error message. ...
1.3 logout (request) User Cancellation
from django.contrib.auth import logout def logout_view(request): logout(request) # Redirect to a success page.
This function accepts an httprequest object and has no return value. When this function is called, all session information of the current request is cleared. This function does not return an error even if the user does not log on.
User object
User object attribute: username, password (required) password is saved to the database by hash algorithm
2.1 is_authenticated () of the user object ()
If it is a real user object, the return value is always true. This is used to check whether the user has passed the verification.
Passing authentication does not mean that the user has any permissions, or even does not check whether the user is activated. This only indicates that the user has successfully passed the verification. This method is very important and request is used in the background.
User. is_authenticated () determines whether the user has logged on. If it is true, the request. User. name can be displayed to the foreground.
Requirements:
1. You can only access some pages after logging in,
2. If the user does not log on, he or she will directly jump to the logon page.
3. After logging on to the logon page, the user automatically jumps to the previously accessed address.
Method 1:
def my_view(request): if not request.user.is_authenticated(): return redirect(‘%s?next=%s‘ % (settings.LOGIN_URL, request.path))
Method 2:
Django has designed a decorator for us: login_requierd ()
from django.contrib.auth.decorators import login_required @login_requireddef my_view(request): ‘‘‘
If the user does not log on, the default Django logon URL '/accounts/login/' will be redirected (this value can be modified through login_url in the settings file ). And pass the absolute path of the current access URL (after successful login, it will be redirected to this path ).
2.2 create a user
Use the create_user auxiliary function to create a user:
from django.contrib.auth.models import Useruser = User.objects.create_user(username=‘‘,password=‘‘,email=‘‘)
2.3 check_password (password)
When a user needs to change the password, he must first input the original password. If the given string passes the password check, true is returned.
2.4 Change Password
Use set_password () to change the password
user = User.objects.get(username=‘‘)user.set_password(password=‘‘)user.save
2.5 simple example
Registration:
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‘ else: new_user = User.objects.create_user(username=username, password=password,email=email) new_user.save() return redirect(‘/book/‘) content = { ‘state‘: state, ‘user‘: None, } return render(request, ‘sign_up.html‘, content)
Registration Code
Change Password:
@login_requireddef 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‘ else: user.set_password(new_password) user.save() return redirect("/log_in/") else: state = ‘password_error‘ content = { ‘user‘: user, ‘state‘: state, } return render(request, ‘set_password.html‘, content)
Password Change code
14 Django User Authentication Component