django auth module built

Certification landed
during the user login validation, if it is to write code, you must first query the database to see if the user name entered by the user exists in the database;
if the user exists in the database, and then verify the password entered by the user, As a result you should write a lot of code yourself.
In fact, Django has provided a built-in user authentication function.
In use "python manage.py makemigrationss", and "python manage.py migrate"after the completion of the migration database
based on the profile settings.pydatabase to generate segment data table already contains 6 tables authentication data, respectively,

  • auth_user
  • auth_group
  • auth_group_permissions
  • auth_permission
  • auth_user_groups
  • auth_user_user_permissions

User authentication data table is auth_user
to be used as the authentication function Django, first import authmodule

from django.contrib import auth         #导入auth模块

django.contrib.authProvides a lot of ways, we used three methods:
the authenticate ()
provides user authentication, which validates the username and password are correct, it normally takes two keyword arguments username and password
if authenticated, the authenticate()function returns a User object .
authenticate()Function to set a property identified on the User object, this attribute identifies verified through the database user name and password.
When we attempted to land a take out from the database directly without going through authenticate()the time of the User object error.
use:

    user=authenticate(username="uaername",password="password")
    
    login(HttpResponse,user)

This function takes an HttpRequestobject and through a authenticate()function Certified User object
landing user login (request)
This function uses Djangothe sessionframework to an authenticated user on the additional session_idinformation.
use:

    from django.shortcuts import render,redirect,HttpResponse
    
    from django.contrib.auth import authenticate,login
    
    def auth_view(request):
        username=request.POST.GET("usernmae")       # 获取用户名
        password=request.POST.GET("password")       # 获取用户的密码
    
        user=authenticate(username=username,password=password)  # 验证用户名和密码,返回用户对象
    
        if user:                        # 如果用户对象存在
            login(request,user)         # 用户登陆
            return redirect("/index/")
    
        else:
            return HttpResponse("用户名或密码错误")

logout (request) Logout
This function takes a HttpResponsetarget, returns no value.
When the function is called, session information of all the current request is cleared.
Even if the current user is not logged, no error will call the function.
use:

    from django.shortcuts import render,redirect,HttpResponse
    
    from django.contrib.auth import authenticate,login,logout
    
    def logout_view(request):
        
        logout(request)     # 注销用户
        
        return redirect("/index/")

user object is_authenticated ()
requires:

  • Users to access certain pages after landing
  • Will jump directly to the login page if the user does not have access to the landing page should have to login to access the
  • After a user visited before landing the landing page, the page will automatically jump to

method one:

    def view1(request):
        
        if not request.user.is_authenticated():
            return redirect("/login/")

Method two:
Use Django's login_requierd()decorators
use:

    from django.contrib.auth.decorators import login_required
    
    @login_required
    def views(request):
        pass

If the user is not logged in, you'll jump to the URL of Django's default landing"/accountss/login/"

login视图函数可以在settings.py文件中通过LOGIN_URL修改默认值

Upon successful login, you will be redirected to the original path.
user objects
User object properties: username, password is required.

password用哈希算法保存到数据库中
  • is_staff: to determine whether the user has administrative rights website
  • is_active: determine whether to allow user login, set when the user can not delete the "False" to prevent users from landing

Methods User object
is_authenticated ()
if it is through auththe function returns true User object, the return value was True. This method checks whether the user has passed the certification.
is_authenticated()Function return value is True, indicating a successful authentication by the user.
Create a user
using the create_userCreate a user helper

from django.contrib.auth.models import User
user=User.objects.create_user(username="username",password="password")

set_password(password)

Use this method to change the password
to use:

    from django.contrib.auth.models import User
    
    user=User.objects.get(username="username")      # 获取用户对象
    user.set_password(password="password")          # 设置对象的密码
    
    user.save()

check_password (password)
the user wants to change the password when the user must first enter the old password.
If you enter the old password through password authentication, returns True.

Create a new user

    from django.shortcuts import render,redirect,HttpResponse
    from django.contrib.auth.models import User
    
    def create_user(request):
    
        msg=None
    
        if request.method=="POST":
            username=request.POST.get("username"," ")           # 获取用户名,默认为空字符串
            password=request.POST.get("password"," ")           # 获取密码,默认为空字符串
            confirm=request.POST.get("confirm_password"," ")    # 获取确认密码,默认为空字符串
    
            if password == "" or confirm=="" or username=="":   # 如果用户名,密码或确认密码为空
                msg="用户名或密码不能为空"
            elif password !=confirm:                            # 如果密码与确认密码不一致
                msg="两次输入的密码不一致"
            elif User.objects.filter(username=username):        # 如果数据库中已经存在这个用户名
                msg="该用户名已存在"
            else:
                new_user=User.objects.create_user(username=username,password=password)  #创建新用户 
                new_user.save()
            
                return redirect("/index/")
        
        return render(request,"login.html",{"msg":msg})

Examples Second, the use login_required装饰器to change password

    from django.shortcuts import render,redirect,HttpResponse
    from django.contrib.auth import authenticate,login,logout
    from django.contrib.auth.decorators import login_required
    from django.contrib.auth.models import User
    
    @login_required
    def change_passwd(request):
        user=request.user       # 获取用户名
        msg=None
    
        if request.method=='POST':
            old_password=request.POST.get("old_password","")    # 获取原来的密码,默认为空字符串
            new_password=request.POST.get("new_password","")    # 获取新密码,默认为空字符串
            confirm=request.POST.get("confirm_password","")     # 获取确认密码,默认为空字符串
    
            if user.check_password(old_password):               # 到数据库中验证旧密码通过
                if not (new_password and confirm):                     # 新密码或确认密码为空
                    msg="新密码不能为空"   
                elif new_password != confirm:                   # 新密码与确认密码不一样
                    msg="两次密码不一致"
    
                else:
                    user.set_password(new_password)             # 修改密码
                    user.save()
    
                    return redirect("/index/")
            else:
                msg="旧密码输入错误"
    
        return render(request,"change_passwd.html",{"msg":msg})

Guess you like

Origin www.cnblogs.com/zhaogang0104/p/11906748.html