一.在urls中写路由
二.返回登录页面(login.html中写前端代码)
- username(用户名)
- password(密码)
- validCode(验证码)
-submit(提交按钮)
-submit -前端:显示的验证码图片 <div class="col-md-6"> <img class="validCode_img" src="/get_validCode_img/" alt="" width="200px" height="50px"> </div>
-后端: 方式一:以二进制打开一个图片路径,获取内容 返回给前端 import os path=os.path.join(settings.BASE_DIR,"blog","static","img","egon.jpg") with open(path,"rb",)as f: data = f.read()
方式二:导入Image,还是以二进制打开一个图片路径,获取内容,返回给前端 from PIL import Image img=Image.new(mode="RGB",size=(120,40),color="blue") f = open("validCode.png","wb") img.save(f,"png") with open("validCode.png","rb") as f: data = f.read()
方式三: from io import BytesIO //导入文件句柄的对象和Image from PIL import Image img = Image.new(mode="RGB",size=(120,40),color="yellow") //创建一个img图片的对象 f=BytesIO() //创建一个内存句柄的对象 img.save(f,"png") data = f.getvalue()
方式四: //创建一个img对象,获取一个画笔,创建字体font。定义一个列表,用for循环随机取出数字或者字母 from io import BytesIO import random from PIL import Image,ImageDraw,ImageFont img = Image.new(mode="RGB",size=(120,40),color=(random.randint(0,255),random.randint(0,255),random.randint(0,255))) draw = ImageDraw.Draw(img,"RGB") #获取一个画笔 font = ImageFont.truetype("blog/static/font/kumo.ttf",28) valid_list = [] for i in range(4): random_num = str(random.randint(0,9)) random_lower_zimu = chr(random.randint(65,90)) random_upper_zimu = chr(random.randint(97,122)) random_char = random.choice([random_num,random_lower_zimu,random_upper_zimu]) draw.text([4+i*24,10],random_char,(random.randint(0,255),random.randint(0,255),random.randint(0,255)),font=font) valid_list.append(random_char) f=BytesIO() //拿到一个句柄对象 img.save(f,"png") //用什么格式保存该图片 data = f.getvalue() valid_str ="".join(valid_list) print(valid_str) request.session["keepValidCode"]=valid_str return HttpResponse(data) def index(request): return render(request,"index.html") 返回验证码并且把验证码写入session
三.点击submit提交
-ajax向后端提交
前端:(login.html.)
<script> $("#subBtn").click(function () { $.ajax({ url: "/login/", type: "POST", data: { "username": $("#username").val(), "password": $("#password").val(), "validCode": $("#validCode").val(), "csrfmiddlewaretoken": $("[name='csrfmiddlewaretoken']").val(), }, success: function (data) { console.log(data); var response = JSON.parse(data); if (response["is_login"]) { location.href = "/index/" } else { $(".error").html(response["error_msg"]).css("color", "red") } } }) }) </script>
后端:(在views中:)
-判断是否是ajax请求 if request.is_ajax(): - 获取用户名 密码 验证码 -username = request.POST.get("username") -password = reuqest.POST.get("password") -validCode = request.POST.get("validCode") -判断验证用户信息是否存在 -login_response = {"is_login":False,"error_msg":None} - 前端获取到的验证码和后端session的验证码是否相同 如果相同: 用户名和密码和数据库中是否匹配 如果不同: obj[error_msg] = "username or password error" 返回前端
if validCode.upper() == request.session.get("keepValidCode").upper(): user = auth.authenticate(username=username, password=password) if user: login_response["is_login"] = True auth.login(request, user) else: login_response["error_msg"] = "username or password error" else: login_response["error_msg"] = "validCode error" import json return HttpResponse(json.dumps(login_response)) return render(request, "login.html")