1. User authentication
1.1 auth module
from django.contrib import auth Many methods are provided in this module
1.1.1authenticate()
user = authenticate(username='someone',password='somepassword') Verifying that the username and password are correct generally requires two keyword parameters, username and password. Authentication passes and the return value is a User object.Incorrect username or password, returning None. User name and password are correct user.is_authenticated=True user.is_anonymous=false authenticate() sets a property on the User object that identifies the back-end that authenticates the user and is required during subsequent logins. If we use filter() to fetch the User object directly from the database (we don't use the authenticate() method to get the User object), it won't work.
1.1.2login(HttpRequest,user)
This function accepts one HttpRequest Object and Pass authenticate()Verified User Object. //This function uses django's session framework to add session id and other information to authenticated users 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.1.3 logout (request) logout user
from django.contrib.auth import logout def logout_view(request): logout(request) # Redirect to a success page. This function accepts an HttpRequest object and does not return a value. When this function is called, all session information currently requested is deleted. Even if the user is not logged in, using this function will not cause an error.
1.2User Object
User object properties: username, password (saved to database with hash algorithm)
1.2.1user.is_authenticated
Check if the user has been suthenticate d. user = auth.authenticate(username=user,password=pwd) print(user.is_authenticated) print(user.is_anonymous) The username and password are correct. user.is_authenticated=True, user.is_anonymous=False
Requirement: 1.Users will not be able to access other pages until they log in 2.If you are not logged in, jump to the login page 3.Users automatically jump to previously visited addresses after they log on to the login page //Method 1: def index(request): # No login, first visit index page, request.user as follows print(request.user) # AnonymousUser print(request.user.is_anonymous) # true print(request.user.is_authenticated) # false # If the user logs in successfully, is_authenticated returns true and request.user.is_anonymous returns false if request.user.is_authenticated: return render(request,"index.html") else: return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) # /login/After successful login, you can redirect to/index/in login via return redirect(request.GET.get("next", "/index/")) #request.GET.get("next", "/index/") is set to default to/index/if there is no next key //Method 2: # With this decorator, you don't need to manually determine whether a user is logged in, as with the index method. # If the user is not logged in, automatically jump to the LOGIN_URL path configured in settings.py.The url is http://127.0.0.1:8000/login/?next=/order/ # /login/After successful login, you can redirect to/order/in login via return redirect(request.GET.get("next", "/index/")) @login_required def order(request): return HttpResponse("order") settings.py Configuration in LOGIN_URL = "/login/"
1.2.2 Creating Users
from django.contrib.auth.models import User user = User.objects.create_user(username='',password='',email='')
1.2.3user.check_password()
When a user changes his password, he or she must enter the old password and verify that the old password is entered correctly before he or she is allowed to change it. The old password entered is correct, return True, otherwise return false.
1.2.4 Change Password
user = request.user user.set_password(new_password) user.save
1.2.5 Simple example
"register" 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) return redirect('/book/') content = { 'state': state, 'user': None, } return render(request, 'sign_up.html', content)
"Change Password" @login_required def 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)
1.3 Complete small case
views.py
from django.shortcuts import render,HttpResponse,redirect from django.contrib import auth from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User def login(request): if request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") # Verify that the username and password are correct and, if correct, return the user object user = auth.authenticate(username=user,password=pwd) if user: auth.login(request, user) # Users automatically jump to previously visited addresses after they log on to the login page # If current access/order/, jumps to login, where the url is http://127.0.0.1:8000/login/?next=/order/ # So you can get the path you just visited through request.GET.get("next", "/index/"), # If login is currently accessed directly, it is http://127.0.0.1:8000/login/, after successful access, jump to/index/ next_url = request.GET.get("next", "/index/") return redirect(next_url) # When get requests, return to the login page return render(request, "login.html") def index(request): # If the user logs in successfully, is_authenticated returns true and request.user.is_anonymous returns false if request.user.is_authenticated: return render(request,"index.html") else: return redirect("/login/") # With this decorator, you don't need to manually determine whether a user is logged in, as with the index method. # If the user is not logged in, automatically jump to the LOGIN_URL path configured in settings.py. @login_required def order(request): return HttpResponse("order") def logout(request): auth.logout(request) def reg(request): if request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") user = User.objects.create_user(username=user, password=pwd) return redirect("/login/") return render(request, "reg.html")
settings.py
LOGIN_URL = "/login/"
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} //User name <input type="text" name="user"> //Password <input type="text" name="pwd"> <input type="submit" value="Submit"> </form> </body> </html>
reg.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/reg/" method="post"> {% csrf_token %} //User name <input type="text" name="user"> //Password <input type="text" name="pwd"> <input type="submit" value="register"> </form> </body> </html>
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> </title> </head> <body> {#Backend return request Object, get the user name in the previous paragraph#} <h3>Current User{{ request.user.username }}</h3> <a href="/logout/">Cancellation</a> </body> </html>
"Register your account first,Visit reg"
"login"
"Logon Success"
"View my own full project git Oh"