Browse the catalog
1. auth module
from django.contrib import auth
There are many methods in django.contrib.auth, here are three of the more commonly used ones:
1、authenticate()
Provides user authentication, that is, to verify whether the user name and password are correct, generally requires two keyword parameters of username and password
If the authentication information is valid, a User object is returned. authenticate() will set a property identifier on the User object to prove that the authentication backend authenticates the user, and this information is required in the subsequent login process. When we try to log in to a User object that is directly retrieved from the database without authenticate(), an error will be reported! !
user = authenticate(username='someone',password='somepassword')
Returns True if the two keyword arguments of username and password match those in the database, and returns None if there is no such user.
2、login(request,user)
This function accepts an HttpRequest object, and an authenticated User object
This function uses Django's session framework to attach information such as session id 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. ...
3. logout (request) to log out the 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 returns no value. When this function is called, the session information of the current request will be cleared. Even if the user is not logged in, using this function will not report an error.
4. is_authenticated() of the user object
Require:
1 Users can only access certain pages after logging in,
2 If the user visits the page without logging in, jump directly to the login page
3 After the user completes the login in the jumped login interface, the user will automatically access and jump to the previously visited address
method one:
def my_view(request): if not request.user.is_authenticated(): return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
Method Two:
Django has designed a decorator for us in this case: login_requierd()
from django.contrib.auth.decorators import login_required @login_required def my_view(request): ...
If the user is not logged in, it will jump to the django default login URL '/accounts/login/ ' (this value can be modified in the settings file through LOGIN_URL). And pass the absolute path of the current access url (after successful login, it will be redirected to this path).
Second, the user object
User object attributes: username, password (required) password is saved to the database with a hash algorithm
is_staff : Whether the user has administrative rights to the site.
is_active : Whether to allow the user to log in, set to ``False``, you can prohibit the user from logging in without deleting the user
1、is_authenticated()
If it is a real User object, the return value is always True. Used to check whether the user has been authenticated.
Authenticating does not mean that the user has any permissions, nor even checking if the user is active, it just means that the user has successfully authenticated. This method is very important. In the background, use request.user.is_authenticated() to determine whether the user is logged in. If true, request.user.name can be displayed to the foreground
2. Create a user
Use the create_user helper function to create users:
from django.contrib.auth.models import User user = User.objects.create_user(username='',password='',email='')
3、check_password(passwd)
用户需要修改密码的时候 首先要让他输入原来的密码 ,如果给定的字符串通过了密码检查,返回
True
4. Change the password
Use set_password() to change the password
user = User.objects.get(username='') user.set_password(password='') user.save()
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) new_user.save() 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)