• 登入认证


    一.自定义认证方法  

    models.py

    class Administrator(models.Model):
        username = models.CharField(max_length=32)
        password = models.CharField(max_length=32)

    views.py

    #登入函数 根据post请求拿到用户信息,从数据库验证后将session的 is_login字段设置成True,并返回默认首页
    def
    login(request): message = "" v = request.session print(type(v)) from django.contrib.sessions.backends.db import SessionStore if request.method == "POST": user = request.POST.get('user') pwd = request.POST.get('pwd') c = models.Administrator.objects.filter(username=user, password=pwd).count() if c: request.session['is_login'] = True request.session['username'] = user rep = redirect('/index.html') return rep else: message = "用户名或密码错误" obj = render(request,'login.html', {'msg': message}) return obj #注销函数 清除session信息 def logout(request): request.session.clear() return redirect('/login.html') #验证装饰器 def auth(func): def inner(request, *args, **kwargs): is_login = request.session.get('is_login') if is_login: return func(request, *args, **kwargs) else: return redirect('/login.html') return inner

    #进入首页时需要验证用户是否登入
    @auth
    def index(request):
    pass

    二.Django自带的登入

       

    from django.views import View
    from django.contrib.auth.mixins import LoginRequiredMixin
    from  django.contrib import auth
    from django.contrib.auth.decorators import login_required
    def login(request): if request.method=="GET": error_msg="请登录" return render(request,'index/login.html',{"error_msg":error_msg}) if request.method=="POST": username = request.POST.get("username", "") password = request.POST.get("password", "")
    #验证用户名密码 user
    =auth.authenticate(username=username,password=password)
    if user:
    #验证后用户登入
    auth.login(request,user)
    return render('index.html')
    # auth.logout() 用户退出

    #CBV 模式的认证 继承系统的认证视图
    class index(LoginRequiredMixin,View):
    def get(request):
    pass
    #FBV 模式的认证   django自带的装饰器
    @login_required
    def index(request):
        pass
  • 相关阅读:
    请说出这些测试最好由那些人员完成,测试的是什么?
    测试结束的标准是什么?
    你的测试职业发展目标是什么?
    elementui医疗
    医疗前端
    spring创建对象3种方式
    idea-git
    eclipse-git
    ArrayList01
    单体权限
  • 原文地址:https://www.cnblogs.com/harveyjie/p/9766360.html
Copyright © 2020-2023  润新知