Django's auth module

Django built a authmodule to help users achieve registration, login, logout and change passwords and other features to help developers save a lot of effort.

auth module

When you create a model, Django will generate a file named internal auth_userdata tables for storing user authentication information.

auth Module provides a series of methods, need to import prior to use:

from django.contrib import auth

authenticate() 方法

Provide user authentication, verify the user name and password are correct and so on. If successful, it returns a Userobject.

from django.contrib import auth

def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

         # 用户认证,验证用户名、密码是否正确,并返回一个 user 对象
         # username、password 字段对应 auth_user 表中相应字段
        user_obj = auth.authenticate(username=username, password=password)

login () method

Implement user login function is generated for the user to log in the background sessiondata.

from django.contrib import auth
auth.login(request, user_obj)

from django.contrib.auth import login
login(request, user_obj)

It accepts two parameters, one of the first HTTPRequestobject and a target authenticated user (i.e., authenticate()authenticated user object).

from django.contrib import auth

def login(request):
    """登录"""
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        # 用户认证,验证用户名、密码是否正确,并返回一个 user 对象
        user_obj = auth.authenticate(username=username, password=password)
        if user_obj:
            # 将验证成功的用户封装到 request.user 对象中
            auth.login(request, user_obj)
            return redirect('home')
        else:
            return '错误信息'
    return render(request, 'login.html')

Successful user authentication objects, execute login()methods, implement the login function, otherwise it returns an error message.

Tips

Executed login()method of user objects can pass request.userto get the currently logged in user object, thus removing information about the user, otherwise it will be made an anonymous user object AnonymounsUser Object.

login(request, user_obj)
# 获得当前登录用户对象
user = request.user
# 获得当前登录用户对象的用户名
username = request.user.username

logout () method

The method enables cancellation function, clear the current logged-in user database sessiondata, receiving a HttpRequesttarget, returns no value.

from django.contrib import auth

def logout(request):
    """注销"""
    auth.logout(request)
    # 注销后重定向到登录页面
    return redirect('login')

is_authenticated 属性

Determine whether the current user is authenticated as a Boolean value.

def home(request):
    """首页"""
    ret = request.user.is_authenticated
    print(ret)      # True

login_required () method

auth template provided by a decorator tool that can easily add a login check for a view.

  • If the user is not logged, the default will jump to accounts/login/, and pass the url to access the current absolute path.
  • Jump custom path, simply settings.pyadd:
# 当用户没有登录,访问某个视图时将会跳转到登录页面
LOGIN_URL = '/login/'
from django.contrib.auth.decorators import login_required

# 添加装饰器
@login_required
def home(request):
    """首页"""

    return render(request, 'home.html')

When a user accesses homethe page, if not logged'll jump to the login page, otherwise homethe page.

User-related

About registration of all related described above, the following will describe how to create auth_usercreate users, change passwords, verify the password.

create_superuser () method

The method for creating a super-user, receiving username、passwordtwo required parameters. Effect performed python manage.py createsuperuserequivalents.

from django.contrib.auth.models import User

user_obj = User.objects.create_superuser(username='用户名',password='密码',email='邮箱',...)

create_user () method

General create_superuser()method is rarely used, is the most commonly used create_user()method, it will create a normal user, often used in registration view.

Create the required field of the user, should auth_userthe corresponding data fields in the table.

from django.contrib.auth.models import User

def signup(request):
    # 创建新用户
    user_obj = User.objects.create_user(username='lila', password='1234')

    return HttpResponse('创建成功')

Tips

Newly created user, stored in the auth_userpassword data in the table is encrypted.

check_password () method

Check the login user password is correct, we need to request the current user's password.

from django.contrib.auth.models import User

def signup(request):
    # 创建新用户
    user_obj = User.objects.create_user(username='lila', password='1234')
    
    ret = user_obj.check_password('123456')
    print(ret)      # False
    return HttpResponse('创建成功')

The password is correct return True, otherwise False.

Or whether the correct original password for user objects check the current request:

obj = request.user.check_password(raw_password='原始密码')

set_password () method

This method is used to change the password, to receive a new password as an argument to finally be sure to perform save()preservation methods, otherwise invalid.

def set_password(request):
    """
    修改密码,request.user 中封装了已认证且执行了登录功能的用户对象
    :param request: 
    :return: 
    """
    request.user.set_password('12')
    password = request.user.password
    request.user.save()
    print(password)

    return HttpResponse('修改成功')

Change Password Examples

This example only applies to logged-in users, change passwords internally, unregistered users will jump to the login page.

from django.shortcuts import render, redirect, HttpResponse
from django.contrib.auth.decorators import login_required

@login_required
def set_password(request):
    """
    修改密码,request.user 中封装了已认证且执行了登录功能的用户对象
    :param request:
    :return:
    """
    user = request.user
    ret = {'message': None}
    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:
                ret['message'] = '新密码不能为空'
            
            elif new_password != repeat_password:
                ret['message'] = '两次密码输入不一致'
            else:
                user.set_password(new_password)
                user.save()
                return redirect('login')
        else:
            ret['message'] = '原密码不正确'
    return render(request, 'set_password.html', ret)

auth module expansion

Since the auth template auth_userdata table fields are fixed, so when we use the auth module, you want to add additional fields, they need to be expanded.

Expand in two ways:

  • Model in a new table, and auth_userthe associated table one
  • Inherit the built-in AbstractUserclasses: Common
  1. Model models.pyin a new class that inherits from AbstractUser:
from django.contrib.auth.models import User, AbstractUser   # 导入 AbstractUser 类


class UserInfo(AbstractUser):
    """
    继承 AbstractUser
    新增字段:phone、addr
    """
    phone = models.CharField(max_length=11, verbose_name='手机号码')
    addr = models.CharField(max_length=128, verbose_name='家庭地址')
  1. Configuration settings.py

The new class inheritance AbstractUser, will expand the coverage auth_usertable, so you need to configure settingsthe default authentication certification know which table to use.

# settings.py
# 在最后添加如下代码
AUTH_USER_MODEL = 'app名.新增的类名'

AUTH_USER_MODEL = 'app.UserInfo'    # 示例
  1. Migration Data Sheet
python manage.py makemigrations
python manage.py migrate
  1. Create a user

After the expansion of auth module, used no longer the original auth_usertable, but a new table app.UserInfotable, so when creating the user should pay attention to.

# 拓展之前
from django.contrib.auth.models import User
user_obj = User.objects.create_user(username='lila', password='1234')

# 拓展之后
from app.models import UserInfo
user_obj = UserInfo.objects.create_user(username='lila', password='1234')

Tips

  • If the migration has been a model, expand auth module, you need to migrationsfolder files (such as: 0001_initial.pyfile deletion), otherwise it will be reported ValueError: Related model u'app.model' cannot be resolved.
  • If no migration model, then the normal execution can be.

Guess you like

Origin www.cnblogs.com/midworld/p/10992027.html