登陆验证码
带验证码的登陆页面:
login页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> <script src="/static/dist/js/jquery-3.1.1.js"></script> <script src="/static/dist/js/bootstrap.js"></script> <link rel="stylesheet" href="/static/dist/css/bootstrap.css"> <link rel="stylesheet" href="/static/css/login.css"> </head> <body> <div class="container"> <div class="row"> <div class="col-md-5 col-md-offset-3"> <form> {% csrf_token %} <div class="form-group"> <label for="username">用户名</label> <input type="text" class="form-control" id="username" placeholder="username"> </div> <div class="form-group"> <label for="password">密码</label> <input type="password" class="form-control" id="password" placeholder="password"> </div> <div class="row validCode"> <div class="col-md-6"> <div class="form-group"> <label for="validCode">验证码</label> <input type="text" class="form-control validCode_text" id="validCode" placeholder="validCode"> </div> </div> <div class="col-md-6"> <img class="validCode_img" src="/get_validCode_img/" alt="" width="200px" height="50px"> </div> </div> <input type="button" value="submit" class="btn btn-primary" id="subBtn"><span class="error"></span> </form> </div> </div> </div> <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> </body> </html>
views页面:
from django.shortcuts import render,HttpResponse,redirect from django import forms # Create your views here. from blog.forms import * from blogCMS import settings from django.contrib import auth def login(request):#登陆页面 # if request.is_ajax(): if request.is_ajax(): username=request.POST.get("username") password=request.POST.get("password") validCode=request.POST.get("validCode") login_response={"is_login":False,"error_msg":None} 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) # session request.session[is_login]=True 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") def get_validCode_img(request):#生成验证码的 # 方式1: # import os # path= os.path.join(settings.BASE_DIR,"blog","static","img","egon.jpg") # # with open(path,"rb") as f: # data=f.read() # 方式2: # from PIL import Image # # img=Image.new(mode="RGB",size=(120,40),color="green") # # f=open("validCode.png","wb") # img.save(f,"png") # # with open("validCode.png","rb") as f: # data=f.read() # 方式3: # from io import BytesIO # # from PIL import Image # img = Image.new(mode="RGB", size=(120, 40), color="blue") # f=BytesIO() # img.save(f,"png") # data=f.getvalue() # return HttpResponse(data) # 方式4 : 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",25) valid_list=[] for i in range(5): 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([5+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) return HttpResponse(data) def index(request):#登陆页面 if not request.user.is_authenticated(): return redirect("/login/") return render(request,"index.html") def log_out(request):#注销登陆 auth.logout(request) return redirect("/login/") def article(request): return render(request,"article.html")
注:可以在页面上用找出是谁登陆的
<h1>{{ request.user.username }}</h1>这个是在模板渲染里用