[py][mx]django自定义认证类

创建自定义验证用户名密码类CustomBackend

users/views.py

from django.contrib.auth import authenticate, login
from django.contrib.auth.backends import ModelBackend
from django.shortcuts import render

# Create your views here.
from users.models import UserProfile

class CustomBackend(ModelBackend):  # 继承认证类,diy它
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:  # 验证用户名密码 否则返回None
            user = UserProfile.objects.get(username=username)  # 表示有这个用户 查处自定义usermodel的用户名,
            if user.check_password(password):  # 表示这个用户密码正确, 这里django存储密码是加密的,必须用其下这个方法加密后比对是否正确
                return user
        except Exception as e:
            return None  # 密码错误返回None

def user_login(request):
    if request.method == "POST":
        user_name = request.POST.get("username", "")
        pass_word = request.POST.get("password", "")
        user = authenticate(username=user_name, password=pass_word)
        if user is not None:  # 用户名密码验证成功
            login(request, user)  # django执行用户登录
            return render(request, "index.html")
        else:
            return render(request, "index.html", {})

    elif request.method == "GET":
        return render(request, "login.html", {})

users/settings.py

AUTHENTICATION_BACKENDS = ('users.views.CustomBackend',)

断点调试, 确实已经用了我们自定义的认证类.

允许用户名用邮箱登录

且的关系
user = UserProfile.objects.get(username=username,email=username) 

或的关系: django自带了Q实现
from django.db.models import Q

user = UserProfile.objects.get(Q(username=username) | Q(email=username)) 

users/views.py完整的

from django.contrib.auth import authenticate, login
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

class CustomBackend(ModelBackend):  # 继承认证类,diy它
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:  # 验证用户名密码 否则返回None
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))  # 表示有这个用户 查处自定义usermodel的用户名,
            if user.check_password(password):  # 表示这个用户密码正确, 这里django存储密码是加密的,必须用其下这个方法加密后比对是否正确
                return user
        except Exception as e:
            return None  # 密码错误返回None

前端输错用户名密码错误提示

users/views.py

def user_login(request):
    if request.method == "POST":
        user_name = request.POST.get("username", "")
        pass_word = request.POST.get("password", "")
        user = authenticate(username=user_name, password=pass_word)
        if user is not None:  # 用户名密码验证成功
            login(request, user)  # django执行用户登录
            return render(request, "index.html")
        else:
            return render(request, "login.html", {'msg':"用户名或密码错误"})

    elif request.method == "GET":
        return render(request, "login.html", {})

templates/login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
<div>
    <form action="/login/" method="post">
        <p><input type="text" name="username" placeholder="username"></p>
        <p><input type="text" name="password" placeholder="password"></p>
        <p><input type="submit"></p>
        {% csrf_token %}
    </form>
    {{ msg }}
</div>
</body>
</html>

原文地址:https://www.cnblogs.com/iiiiiher/p/8395177.html

时间: 2024-07-29 18:30:11

[py][mx]django自定义认证类的相关文章

[py][mx]django使用class写views-免去判断方法的烦恼

修改views使用class模式 类模式写views - 免去了函数模式的判断的烦恼 users/views.py from django.views.generic import View class UserView(View):#继承了View类,它里面实现get post等方法, 使用类模式写免去了函数模式的判断 def get(self, request): return render(request, "login.html", {}) def post(self, req

Django 自定义分页类

分页类代码: class Page(object): ''' 自定义分页类 可以实现Django ORM数据的的分页展示 输出HTML代码: 使用说明: from utils import mypage page_obj = mypage.Page(total_num, current_page, 'publisher_list') publisher_list = data[page_obj.data_start:page_obj.data_end] page_html = page_obj.

[py][mx]django处理登录逻辑

处理登录逻辑 users/views.py from django.contrib.auth import authenticate, login def user_login(request): if request.method == "POST": user_name = request.POST.get("username", "") pass_word = request.POST.get("password", &

[py][mx]django的cookie和session操作

这玩意可以实现7天免登录等功能. session和cookie机制原理和交互过程 交互过程 ① 客户端访问,无服务端写入的Cookie ② 服务端的Cookie写入浏览器 ③ 浏览器解析Cookie,保存至浏览器文件 ④ 客户端访问,有服务端写入的Cookie ⑤ 服务器获取 django请求中的cookie 第一次访问服务端会给一个csrf的cookie 登录完成后,默认给一个为期半个月的cookie 用于访问别的也没使用. django中cookie与session的实现原理 app默认注册

[py][mx]django分页第三方模块django-pure-pagination

分页模块django-pure-pagination - 一款基于django pagination封装的更好用的分页模块 https://github.com/jamespacileo/django-pure-pagination - 安装 pip install django-pure-pagination views.py from pure_pagination import Paginator, EmptyPage, PageNotAnInteger class OrgView(Vie

[py][mx]django get方法返回login页面

get方法返回login.html users/views.py def login(request): if request.method == "POST": pass elif request.method == "GET": return render(request, "login.html") 前端请求发来request对象里包含了method,path等. 可以debug单步调试看到 users/urls.py from users

[py][mx]django添加后台课程机构页数据-图片上传设置

分析下课程页前台部分 机构类别-目前机构库中没有这个字段,需要追加下 所在地区 xadmin可以手动添加 课程机构 涉及到机构封面图, 即图片上传media设置, 也需要在xadmin里手动添加几条 用xadmin添加数据 所在地区添加 课程机构添加 补充机构类别在model里的字段 class CourseOrg(models.Model): catagory = models.CharField(max_length=20, default="pxjg", choices=((&q

[py][mx]django实现根据城市和课程机构类别过滤

实现根据城市&课程机构过滤 实现点谁谁高亮,支持取交集. 直接上代码吧 本质上是过滤,多层过滤,取交集 def get(self, request): all_orgs = CourseOrg.objects.all() # 所有课程机构 all_citys = CityDict.objects.all() # 所有城市列表 # 取出筛选城市 city_id = request.GET.get("city", "") if city_id: all_orgs

[py][mx]django通过邮箱找回密码

忘记密码处理流程 直接上代码 class ActiveView(View): # 主要功能是修改user_profile里的is_active字段为1 def get(self, request, active_code): all_reocrds = EmailVerifyRecord.objects.filter(code=active_code) if all_reocrds: for record in all_reocrds: email = record.email user = U