On the auth module

auth module

What is Auth module

auth module is the cancellation of the registration login authentication methods such as passwords to modify a package before we have time to carry out these operations, the user must first create a table in the models, you need to own table from a user query after the user has no password user name or password that meets the target, but now have auth module can easily go after verifying the user's login information exists in the database. In addition, auth session also made some packages, we easily check whether the user has logged in.

The method of module common auth

To use the auth module, you must first import auth module

from django.contrib import auth

authenticate方法

Check whether the user exists, if there is a User object is returned, if there is no return None, generally require username, password two key parameters. When we try to log on a take out from the database directly without authenticate () User object will error

class User(View):
    def get(self,request):
        return render(request,'user.html')
    def post(self,request):
        username=request.POST.get('username')
        password=request.POST.get('password')
        user_obj=auth.authenticate(username=username,password=password)
        if user_obj:
            return redirect('/index/')
        return HttpResponse('该账号不存在')

login method

This function takes an HttpRequest object and a User object certified. This function uses Django's session framework to an authenticated user on session_id additional information.

def login(request):
    if request.method=='POST':
        username=request.POST.get('username')
        password=request.POST.get('password')
        user_obj=auth.authenticate(username=username,password=password)
        auth.login(request,user_obj)
        return HttpResponse('登陆成功')
    return render(request,'login.html')

is_authenticated方法

This function can determine whether the user is logged

def my_view(request):
      if not request.user.is_authenticated():
            return redirect('/take/' )

logout method

This function can be used to log off the user, the function accepts an HttpRequest object, no return value. When the function is called, the current request will clear all session information. Even if the user is not logged in, use this function also does not complain

from django.contrib import logout
def logout_view(request):
    logout(request)

Check whether the user is logged decorator

First we have to import

from django.contrib.auth.decorators import login_required

Local Configuration

@login_required(login_url='/.../')

Global Configuration

@login_required

Note: When a user is not logged in, jump url in two ways

  1. Specified by local decorator login_url parameters within the brackets

  2. De-global configuration, in case the user is not logged in, all unified view Jump to a url

    Written in the configuration file on LOGIN_URL = '/ login /'

User Registration

User registration function you want to use auth module will first come into the User

from django.contrib.auth.models import User

create_user

create_user is a way to create a new user auth module, we need to provide the necessary parameters (username, password) and so on.

from django.contrib.auth.models import User
user=User.objects.create_user(username='用户名',password='密码')

create_superuser

create_superuser is a way to create a super user auth module, you need to provide the necessary parameters (username, password), etc.

from django.contrib.auth.models import User
user=User.objects.create_superuser(username='用户名',password='密码')

check_password (password)
a check auth password provided is correct way, the need to provide the password for the current user request.
The password is correct return True, otherwise False.
usage:

ok = user.check_password('密码')

set_password (password)
method modified auth password provided, arranged to receive a new password as a parameter.
Note: After setting sure to call the save method for user objects! ! !

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.

Extend 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 field to store the user's mobile phone number, 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):
"""
用户信息表
"""
nid = models.AutoField(primary_key=True)
phone = models.CharField(max_length=11, null=True, unique=True)
def __str__(self):
return self.username

Note:
According to the above mode extends the built-in table auth_user after, be sure to tell Django in settings.py, I now make
with my newly defined UserInfo table to do user authentication. Worded as follows:

# 引用Django自带的User表,继承使用时需要设置
AUTH_USER_MODEL = "app名.UserInfo"

Note again:
Once we specify table new authentication system used, we need to re-create the table in the database, rather than following the
continued use of the original default auth_user the table.

Guess you like

Origin www.cnblogs.com/MrYang161/p/11898950.html