auth module
auth module is a package of login authentication method, itself is an object, the user can obtain more information, with the module auth may verify whether the login information exists in the database, you can also check whether the user has logged in, password verification
auth method
- Importing
from django.contrib import auth
1、authenticate()
Provides user authentication to verify the user name and password are correct, if the information is valid will return a user object
user =authenticate(username='',password='')
2、login(HttpRequest,user)
Takes an HttpRequest object and a User object certified, this function uses django framework of the session to an authenticated user on the additional session, id and other information
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)
else:
pass
3, logout (request) Logout
Accepts an HttpRequest object, no return value, the function is called, the current request information session will clear
from django.contrib.auth import logout
def logout_view(request):
logout(request)
4, is_authenticated user object ()
To access some of the pages after the user logs
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
pass
def my_view(request):
if not user.is_authenticated():
pass
user objects
Attributes: Save username, password, where password using a hashing algorithm to database
is_staff: whether the user has administrative rights website
is_active: whether to allow user login, set to 'False', you can not delete users to disable user login
1, create_user create user
from django.contrib.auth.models import User
user=User.object.create_user(username='',password='',email='')
2, check_password (password) check the old password
user=User.objects.get(username='')
if user.check_password(password):
pass
3, set_password () Change Password
user=User.objects.get(username='')
user.set_password(password='')
user.save
Inherit auth method
1, into a AbstractUser class, and write a custom class that inherits AbstractUser
from django.contrib.auth.models import AbstractUser
class UserInfo(AbstractUser):
pass
2, the configuration file in setting.py
AUTH_USER_MODEL=''