auth module (for users)

What is Auth module

Use auth module must not be written in their own part of a full part with others

Django Auth module is 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 achieve, including user registration, user login, user authentication, log off, change passwords and other functions, this really is a troublesome thing yet.

Django as a framework for the ultimate perfectionist, of course, also think of these pain points users. It built a powerful user authentication system --auth, it defaults to auth_user table to store user data.

How to use the auto module

1. Create a super administrator to log in django admin background management for landing

Next, create create a super administrator

Note: to set a password when the password is not simple, and requires only 8 characters can be created, and the password is encrypted and can not directly view

You can see the contents of the table after successfully created, the following are all available fields.

After landing




Common module auth method

from django.contrib import auth

authenticate () (example: landing)

Role: check whether the user exists

This method will return a value in the case where the presence of the data object itself is returned, the condition is not satisfied directly returns None

Provides user authentication function, namely to verify the user name and password are correct, it normally takes username, password two key parameters.

If authentication is successful (valid user name and password are correct), it will return a User object.

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.

usage:

user = authenticate(username='usernamer',password='password')

<form action="" method="post">
    {% csrf_token %}
    <p>username:<input type="text" name="username"></p>
    <p>password:<input type="text" name="password"></p>
    <p><input type="submit" value="提交"></p>
</form>

login(HttpRequest, user)

Role: save the user's log-in status

auth.login(request,user_obj)  # 执行完这一句之后 只要是能够拿到request的地方 
        # 都可以通过request.user获取到当前登录用户对象

This function takes an HttpRequest object and a User object certified.

This function implements a user login functionality. Essentially it generates a session related data for the user at the rear end.

Usage: When the implementation of this method, users need to be present, the job

from django.contrib import auth
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)
        print(user_obj)
        print(user_obj.username)
        print(user_obj.password)
        """该方法会主动帮你操作session表 并且只要执行了该方法
            你就可以在任何位置通过request.user获取到当前登录的用户对象
        """
        auth.login(request,user_obj)
        #一定要记录用户状态 才算真正的用户登录
    return render(request,'login.html')

def home(request):
    print(request.user)
    return HttpResponse('哈喽共享你进入home')

is_authenticated()

Role: to determine whether the current user loginrequest.user.is_authenticated()

is true representatives have landed, on behalf of flase not logged in

Used to determine whether the current request certified.

usage:

def index(request):
    print(request.user)  # 直接拿到登录用户的用户对象
    print(request.user.is_authenticated,1)  # 简单快捷的判断用户是否登录
    print(request.user.is_authenticated(),2)
    return HttpResponse('index')

login_requierd decorator

auth provides us with a decorative tool for quick login to add a check to the view.

You must importfrom django.contrib.auth.decorators import login_requierd

usage:

from django.contrib.auth.decorators import login_required
      
@login_required#给下面的视图添加装饰器,没有登陆的话,访问不了
def set_password(request):
    pass

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).

Local Configuration

If you want to customize the login URL, add the parameter back

from django.contrib.auth.decorators import login_required
      
@login_required(login_url="/login/")#给下面的视图添加装饰器,没有登陆的话,访问不了
def set_password(request):
    pass

Global Configuration

If you need to jump all of them write their own designated URL, you need to be modified by LOGIN_URL in settings.py file.

Example:

auto校验全局是否登陆的配置
LOGIN_URL = '/login/'  # 这里配置成你项目登录页面的路由
from django.contrib.auth.decorators import login_required
      
@login_required#这个时候不需要添加参数了
def set_password(request):
    pass

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.

usage:

ok = user.check_password('密码')

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! ! !

usage:

user.set_password(password='')
user.save()

from django.contrib.auth.decorators import login_required
@login_required(login_url='/login')
def set_password(request):
    if request.method == 'POST':
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        # 校验原密码对不对
        is_right = request.user.check_password(old_password)
        #判断密码是否正确,正确返回True
        print(is_right)
        if is_right:
            # 修改密码
            request.user.set_password(new_password)
            # 这个方法,仅仅只会在内存中产生一个缓存
            # 并不会直接修改数据库
            request.user.save()  # 一定要点save方法保存 才能真正的操作数据库
            return redirect('/login/')
    return render(request, 'set_password.html', locals())
<form action="" method="post">
    {% csrf_token %}
    <p>username<input type="text" disabled value="{{ request.user.username }}"></p>{#disabled名字不能修改#}
    <p><input type="text" name="old_password"></p>
    <p><input type="text" name="new_password"></p>
    <input type="submit">
</form>

create_user()

Way to create a new user auth offer, it is necessary to provide the necessary parameters (username, password) and so on.

usage:

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) and so on.

usage:

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

1572525572189

logout(request)

This function takes a 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.

usage:

from django.contrib.auth import logout
   
def logout_view(request):
  logout(request)
  # Redirect to a success page.

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 auth_user table (Extended User table)

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.

After you inherited AbstractUser emphasize your custom fields in the table must not conflict with the original

from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.

class Userinfo(AbstractUser):
    """
    强调 你继承了AbstractUser之后 你自定义的表中 字段不能跟原有的冲突
    """
    phone = models.BigIntegerField()
    avatar = models.FileField()
    register_time = models.DateField(auto_now_add=True)

    
    def __str__(self):
        return self.username

note

After the expansion of the built-in auth_user above table by the way, be sure to tell Django in settings.py, I now use my newly defined UserInfo table instead of the table do auth_user 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.

another kind

One to one relationship extended field use table

Guess you like

Origin www.cnblogs.com/SkyOceanchen/p/11773692.html