码迷,mamicode.com
首页 > 其他好文 > 详细

django基础~重写登录验证函数

时间:2021-04-05 12:37:18      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:text   登录   定义类   use   elb   rom   持久   覆盖   model   

 
1 重写 authenticate 函数 目的是取代自带的登录校验方式
from django.contrib.auth.backends import ModelBackend, UserModel
from . import models
class CustomBackend(ModelBackend): 继承类
def authenticate(self, request, username=None, password=None, **kwargs):
try:
user = UserProfile.objects.get( Q(username=username) | Q(email=username))
if user.check_password(password): //验证密码
return user
except Exception as e:
return e
#settings.py 覆盖原来的(‘django.contrib.auth.backends.ModelBackend‘,)
AUTHENTICATION_BACKENDS=(
自定义类CustomBackend
)
2 调用
from django.contrib.auth import authenticate
user = authenticate(username=username,password=password)调用上面的自定义函数

login(request,user) 进行登录和持久化操作

3 前端验证是否登录

{% if request.user.is_authenticated %}

{% endif %}

4

 

django基础~重写登录验证函数

标签:text   登录   定义类   use   elb   rom   持久   覆盖   model   

原文地址:https://www.cnblogs.com/danhuangpai/p/14613783.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!