table of Contents
Chapter VII, Ajango comes auth module
First, what is auth
django auth is a built-in user authentication module
We are developing a site, the inevitable need to design websites to achieve the user's system. At this point we need to implement include 用户注册、用户登录、用户认证、注销、修改密码
other functions, this really is a troublesome thing does
Django as a framework for the ultimate perfectionist, of course, will think of these pain points users. It built a powerful user authentication system - auth
it defaults auth_user
table to store user data.
Two, auth module common method
First import module
from django.contrib import auth
authenticate()
login(HttpRequest, user)
logout(request)
is_authenticated()
login_requierd()
create_user()
create_superuser()
check_password(password)
set_password(password)
authenticate()
Verify the user name and password are correct, it normally takes
username 、password
two keyword arguments.authenticate () sets a property on the rear end of the object to identify User has authenticated the user, and the login information in a subsequent process is required.
user = authenticate(username='usernamer',password='password')
login(HttpRequest, user)
This function takes an
HttpRequest
object as well as a certification throughUser
the object.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: #判断user是否存在 存在就能获取 login(request, user)#登录 本质上给后端为这个user 生成session数据 #登陆成功后返回一个sucess的page ... else: # 返回一个user不存在的page ...
logout(request)
There must log off the landing to receive a HttpRequest object, no return value.
When this function is called, the current request will clear the session. Even if the user is not logged in, use this function also does not complain.
from django.contrib.auth import logout def logout_view(request): logout(request) # Redirect to a success page.
is_authenticated()
Used to determine whether the current request certified.
def my_view(request): if not request.user.is_authenticated(): return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) #不通过验证的user会重定向到登录界面 else: ...#返回验证通过后跳转到的页面
login_requierd()
auth provides us with a decorative tool for quick login to add a check to the view.
from django.contrib.auth.decorators import login_required @login_required def my_view(request): ...
Description:
If the user is not logged, it will jump to the django default login URL
'/accounts/login/ '
and pass the current url to access the absolute path (after a successful landing, will be redirected to the path). You need to customize the url you need to log insettings.py
through the fileLOGIN_URL
to be modified. For example,LOGIN_URL = '/login/'
here configured to route the login page of your projectcreate_user()
way to create a new user auth offer, it is necessary to provide the necessary parameters
(username、password)
and so on.from django.contrib.auth.models import User user = User.objects.create_user(username='用户名',password='密码',email='邮箱',...)
create_superuser()
Creating a new super user auth provides a method of providing the necessary parameters
(username、password)
from django.contrib.auth.models import User user = User.objects.create_superuser(username='用户名',password='密码',email='邮箱',...)
check_password(password)
The correct way to check whether a password auth offer, you need to provide the current request the user's password. The password is correct return True, otherwise False.
is_ok = user.check_password('密码') #密码正确is_ok返回True,否则返回False。
set_password(password)
The method of modifying a password provided by the auth received new password to be set as a parameter.
Note: After setting sure to call the save method for user objects! ! !
user.set_password(password='') user.save() #设置完一定要调用用户对象的save方法!!!
Simple Change Password Case
@login_required def set_password(request): user = request.user err_msg = '' 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: err_msg = '新密码不能为空' elif new_password != repeat_password: err_msg = '两次密码不一致' else: user.set_password(new_password) user.save() return redirect("/login/") else: err_msg = '原密码输入错误' content = { 'err_msg': err_msg, } return render(request, 'set_password.html', content)
Properties User objects
User object properties: username, password
is_staff: whether the user has administrative permissions for the site.
is_active: whether to allow user login, set to False, you can stop users from logging in without deleting the user's premises.
Third, expand the default table auth_user
This built-in authentication system so easy to use, but auth_user table fields are fixed those few, I can not bring in the project directly ah!
For example, I want to add a user to store phone number phone
field, how to do?
Smart you may think of the new table and then another one by one to one and a built-in table auth_user association, although this can meet the requirements, but there is no better way to achieve it?
The answer is of course with.
We can inherit the built-in AbstractUser
class to define its own Model class.
This will not only according to the needs of the project design flexible user table, Django can use the strong authentication system.
from django.contrib.auth.models import AbstractUser
class UserInfo(AbstractUser):
"""
用户信息表
"""
id = models.AutoField(primary_key=True)
phone = models.CharField(max_length=11, null=True, unique=True)
def __str__(self):
return self.username
Do not forget to perform data migration command migrate
andmakemigrations
note:
After the expansion of the built-in auth_user above table by the way, be sure to settings.py
tell Django, I now use my newly defined UserInfo
table to do user authentication. Worded as follows:
# 引用Django自带的User表,继承使用时需要设置
AUTH_USER_MODEL = "app名.UserInfo"
Note again:
Once we specify the table new authentication system used, we need to re-create the table in the database, but can not continue to use the original default auth_user the table.