• django,auth认证(注册,登录,修改密码)


    auth是django提供的权限管理系统,可以提供用户身份认证,用户组合权限管理。

    登录认证:

    登录的视图函数:

    def login_auth(request):
        if request.method == "GET":
            return render(request, "login.html", context={"new_time": new_time})
        if request.method == "POST":
            username = request.POST.get("username")
            password = request.POST.get("password")
            print("用户名:{},密码:{}".format(username, password))
            #  todo user认证成功返回对象,认证失败返回空
            user = authenticate(username=username,
                                password=password)
            if user:
                if user.is_active:  # 判断用户是否有效
                    login(request, user=user)  # 登录
                    request.session["user"] = username  # 加session
                    request.session.set_expiry(None)  # 设置session有效期:0为关闭浏览器马上失效,none为永久
                    result = {"code": 0,
                              "msg": "login success!",
                              "data": {"username": username,
                                       "password": password,
                                       }
                              }
                    # return JsonResponse(result)
                    return HttpResponseRedirect("/info/")
            else:
                # return redirect('/login')
                return render(request, "login.html", context={"msg": "用户名或密码错误"})

    登录的html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>登陆接口</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    </head>
    <body>
    <h3 align="center">登录页面</h3>
    <p align="center">{{ new_time }}</p>
    <form action="" method="post">
           <table  align="center">
              <tr>
                 <td>用户名</td>
    
                 <td>
                    <input type="text" name="username" />
                </td>
              </tr>
              <tr>
                 <td>密码</td>
                 <td>
                    <input type="text" name="password"/>
                </td>
               <p style="color: red" align="center">
                    {{msg}}
              </p>
              <tr>
                 <td>
                    <input type="submit" value="登录">
                 </td>
    
              </tr>
            </table>
    </form>
    </body>
    </html>

    显示效果:

    注册认证:

    注册的视图函数:

    def register(request):
        if request.method == "GET":
            return render(request, "register.html", context={"new_time": new_time})
        if request.method == "POST":
            register_name = request.POST.get("registername")
            register_pwd = request.POST.get("registerpwd")
            print("获取到用户输入的用户名是:{}密码是:{}".format(register_name, register_pwd))
            # 通过用户名判断查询账号是否已经注册
            user_list = User.objects.filter(username=register_name)
            if user_list:
                data = {
                    "msg": "account already exists!"
                }
                return render(request, "register.html", context=data)
            elif len(register_pwd) < 6:
                return render(request, "register.html", context={"msg": "密码长度必须大于等于6位"})
    
            elif register_name.strip() != '' and register_pwd.strip() != '':
                user = User.objects.create_user(username=register_name, password=register_pwd)
                regist_result = {
                    "code": 0,
                    "msg": "register success!",
                    "data": {
                        "register_name": register_name,
                        "register_pwd": register_pwd,
                    }
                }
                user.save()
                return JsonResponse(regist_result)
            else:
                data = {"msg": "not null!"}
                return render(request, "register.html", context=data)

    注册的html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>注册接口</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    </head>
    <body>
    <h3 align="center">注册页面</h3>
    <p align="center">{{ new_time }}</p>
    <form action="" method="post">
           <table  align="center">
              <tr>
                 <td>请输入用户名</td>
                 <td>
                    <input type="text" name="registername" />
                </td>
              </tr>
              <tr>
                 <td>请输入密码</td>
                 <td>
                    <input type="text" name="registerpwd"/>
                </td>
              </tr>
              <p style="color: red" align="center">
                    {{msg}}
              </p>
              <tr>
                 <td>
                    <input type="submit" value="注册">
                 </td>
              </tr>
            </table>
    </form>
    </body>
    </html>

    显示效果:

    修改密码:

    修改密码的视图函数:

    @login_required
    def updata_pwd(request):
    if request.method == "GET":
    return render(request, "updata.html", context={"new_time": new_time})
    if request.method == "POST":
    # username = request.POST.get("username")
    password = request.POST.get("password")
    new_password = request.POST.get("new_password")
    username = request.user.username # 获取当前登录用户的用户名
    user = authenticate(username=username,
    password=password)

    print("当前用户登录名是:{}".format(username))

    if not user:
    # todo 如果用户没在user中,证明登录失败,修改密码先判断登录成功,再去修改密码
    return render(request, "updata.html", context={"msg": "原密码错误,请重新输入"})
    else:
    user.set_password(new_password) # 重置密码
    user.save() # todo 一定要保存才会生效
    return render(request, "updata.html", context={"msg": "密码修改成功"})

    修改密码的html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>注册接口</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    </head>
    <body>
    <h3 align="center">注册页面</h3>
    <p align="center">{{ new_time }}</p>
    <form action="" method="post">
           <table  align="center">
              <tr>
                 <td>请输入用户名</td>
                 <td>
                    <input type="text" name="registername" />
                </td>
              </tr>
              <tr>
                 <td>请输入密码</td>
                 <td>
                    <input type="text" name="registerpwd"/>
                </td>
              </tr>
              <p style="color: red" align="center">
                    {{msg}}
              </p>
              <tr>
                 <td>
                    <input type="submit" value="注册">
                 </td>
              </tr>
            </table>
    </form>
    </body>
    </html>

     全部视图代码:

    from django.shortcuts import render, redirect
    from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
    from Hello_Api.models import Register
    from django.contrib.auth.models import User
    from django.contrib.auth import authenticate, login
    from django.contrib.auth.decorators import login_required
    import datetime
    
    # Create your views here.
    
    new_time = datetime.datetime.now()
    
    
    @login_required
    def personinfo(request):
        context = {
            "blog_name": "圆觉",
            "username": "",
            "age": 23,
            "fancy": ["python", "django", "requests"],
            "blog": {"url": "https://www.cnblogs.com/xiamaojjie/",
                     "img": "https://pic.cnblogs.com/avatar/1772245/20191102152106.png",
                     }
    
        }
    
        class Myblog():
    
            def __init__(self):
                self.guangzhu = 3
                self.fensi = 8
    
            def guangzhu(self):
                return self.guangzhu
    
            def fensi(self):
                return self.fensi
    
        myblog = Myblog()  # TODO 实例化对象
    
        context["myblog"] = myblog  # TODO 把对象添加到字典里面,通过类名.取值
    
        return render(request, "personinfo.html", context)
    
    
    def register(request):
        if request.method == "GET":
            return render(request, "register.html", context={"new_time": new_time})
        if request.method == "POST":
            register_name = request.POST.get("registername")
            register_pwd = request.POST.get("registerpwd")
            print("获取到用户输入的用户名是:{}密码是:{}".format(register_name, register_pwd))
            # 通过用户名判断查询账号是否已经注册
            user_list = User.objects.filter(username=register_name)
            if user_list:
                data = {
                    "msg": "account already exists!"
                }
                return render(request, "register.html", context=data)
            elif len(register_pwd) < 6:
                return render(request, "register.html", context={"msg": "密码长度必须大于等于6位"})
    
            elif register_name.strip() != '' and register_pwd.strip() != '':
                user = User.objects.create_user(username=register_name, password=register_pwd)
                regist_result = {
                    "code": 0,
                    "msg": "register success!",
                    "data": {
                        "register_name": register_name,
                        "register_pwd": register_pwd,
                    }
                }
                user.save()
                return JsonResponse(regist_result)
            else:
                data = {"msg": "not null!"}
                return render(request, "register.html", context=data)
    
    
    def login_auth(request):
        if request.method == "GET":
            return render(request, "login.html", context={"new_time": new_time})
        if request.method == "POST":
            username = request.POST.get("username")
            password = request.POST.get("password")
            print("用户名:{},密码:{}".format(username, password))
            #  todo user认证成功返回对象,认证失败返回空
            user = authenticate(username=username,
                                password=password)
            if user:
                if user.is_active:  # 判断用户是否有效
                    login(request, user=user)  # 登录
                    request.session["user"] = username  # 加session
                    request.session.set_expiry(None)  # 设置session有效期:0为关闭浏览器马上失效,none为永久
                    result = {"code": 0,
                              "msg": "login success!",
                              "data": {"username": username,
                                       "password": password,
                                       }
                              }
                    # return JsonResponse(result)
                    return HttpResponseRedirect("/info/")
            else:
                # return redirect('/login')
                return render(request, "login.html", context={"msg": "用户名或密码错误"})
    
    
    @login_required
    def updata_pwd(request):
        if request.method == "GET":
            return render(request, "updata.html", context={"new_time": new_time})
        if request.method == "POST":
            username = request.POST.get("username")
            password = request.POST.get("password")
            new_password = request.POST.get("new_password")
            user = authenticate(username=username,
                                password=password)
            if not user:
                # todo 如果用户没在user中,证明登录失败,修改密码先判断登录成功,再去修改密码
                return render(request, "updata.html", context={"msg": "原密码错误,请重新输入"})
            else:
                user.set_password(new_password)  # 重置密码
                user.save()  # todo 一定要保存才会生效
                return render(request, "updata.html", context={"msg": "密码修改成功"})
  • 相关阅读:
    Python 多线程,文件io
    Python map/reduce函数式编程
    LeetCode 77 组合
    LeetCode 198 打家劫舍
    LeetCode 138 复制带随机指针的链表
    LeetCode 445 两数相加 II
    LeetCode 2 两数相加
    LeetCode 215 数组中的第K个最大元素
    和为S的两个数字
    数组中重复的数字
  • 原文地址:https://www.cnblogs.com/xiamaojjie/p/12587397.html
Copyright © 2020-2023  润新知