ajax 的登录认证

在models中 先创建一个表 

from django.db import models

# Create your models here.
class UserInfo(models.Model):
    username = models.CharField(max_length=32,unique=True)
    password = models.CharField(max_length=32,unique=True)

在setting的文件中的最后一行 配置静态地址

STATICFILES_DIRS=[os.path.join(BASE_DIR,"static")]

在Python Console中用ORM创建一条测试用的用户名和密码, 也可以直接在数据库中添加

from app01.models import UserInfo
UserInfo.objects.create(username="wang",password="wang")

开始写html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/static/js/jquery-3.3.js"></script>
</head>
<body>
<form action="">
    用户名<input type="text" id="user">
    密码<input type="password" id="pwd">
    <input type="submit" value="提交" id="login_btn"><span class="error"></span>
    {% csrf_token %}
</form>

<script>
    $("#login_btn").click(function(){
        //发送Ajax请求登录认证
        $.ajax({
            url:"/login/",
            type:"post",
            data:{
                user:$("#user").val(),
                pwd:$("#pwd").val(),
                csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val()
            },
            success:function(res){
                var res=JSON.parse(res); //反序列化数据  把字符串转换成支持的类型
                console.log(res);

                if (res.user){
                    // 登录成功
                    location.href="/index/"
                }else{
                    //登录失败
                    $(".error").html(res.error).css("color","red");
                    setTimeout(function(){
                        $(".error").html("")
                    },2000)
                }

            }
        })
    })

</script>

</body>
</html>

views视图

from django.shortcuts import render,HttpResponse,redirect
from app01.models import UserInfo


# ajax的用户登录
def login(request):
    if request.method == "POST":
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")

        res = {"user": None, "error": ""}
        user_obj = UserInfo.objects.filter(username=user,password=pwd).first()
        print("user_obj:",user_obj)

        if user_obj:
            res["user"]=user_obj.username
        else:
            res["error"]="用户名和密码不一致"
        return HttpResponse(json.dumps(res))
    return render(request,"login.html")

def index(request):
    return render(request,"index.html")
原文地址:https://www.cnblogs.com/kenD/p/10126063.html