带验证码的登陆页面:
login页面:
Title
views页面:
from django.shortcuts import render,HttpResponse,redirectfrom django import forms# Create your views here.from blog.forms import *from blogCMS import settingsfrom django.contrib import authdef 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")
注:可以在页面上用找出是谁登陆的
{ { request.user.username }}
这个是在模板渲染里用