Django中生成随机验证码
1、html中a标签的设置
1 <img src="/get_validcode_img/" alt="">
2、views中的get2、views中的getvalidcode_img设置
导入文件
1 import json 2 import os 3 import random 4 from django.contrib import auth 5 from django.shortcuts import render, redirect, HttpResponse 6 from django.forms import Form 7 from django.forms import fields 8 from django.forms import widgets 9 from django.core.exceptions import ValidationError 10 from django.conf import settings 11 from PIL import Image, ImageDraw, ImageFont 12 from io import BytesIO
方法配置
1 def get_validcode_img(request): 2 color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) 3 # 生成一个颜色随机的大小为160,30的图片 4 img = Image.new(mode="RGB", size=(160, 30), color=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) 5 # 设置图片的绘制颜色 6 draw = ImageDraw.Draw(img, "RGB") 7 # 设置图片的绘制字体(只写字体名,会默认在系统的Fonts下去找) 8 # font_path = os.path.join(settings.BASE_DIR, "static", "font", "kumo.ttf") 9 # font = ImageFont.truetype(font_path, 25) 10 font = ImageFont.truetype(r‘C:\Windows\Fonts\Arial.ttf‘, 25) 11 # font = ImageFont.truetype(r‘C:\中文\kumo.ttf‘, 25) # 中文路径无法识别 12 13 # 设置图片上的字符串 14 valid_list = [] 15 for i in range(5): 16 random_num = str(random.randint(0, 9)) 17 random_letter_low = chr(random.randint(65, 90)) 18 random_letter_upper = chr(random.randint(96, 122)) 19 random_char = random.choice([random_num, random_letter_low, random_letter_upper]) # 随机选择字符(数字,大小写字母) 20 # 通过draw.text方法,设置图片上字符串的x,y坐标,字符串,颜色,字体(for循环5次,生成5个字符的验证码) 21 draw.text([5+i*25, 10], random_char, (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), font=font) 22 valid_list.append(random_char) 23 # 获取一个内存中的文件句柄 24 f = BytesIO() 25 # 在文件句柄中写入文件 26 img.save(f, ‘png‘) 27 # 取出文件 28 data = f.getvalue() 29 # 转换成字符串 30 valid_str = "".join(valid_list) 31 print(valid_str) 32 33 # 把验证码保存在session中,当用户出入验证码发送请求的时候,把用户输入的数据和session中的验证码做对比 34 request.session["validcode"] = valid_str 35 return HttpResponse(data)
三、 Ajax请求配置
1 $(function(){ 2 $("#login_btn").click(function () { 3 var username = $("#username").val(); 4 var password = $("#password").val(); 5 var validcode = $("#validcode").val(); 6 7 $.ajax({ 8 url: "/login/", 9 type: "POST", 10 data : {"username":username, "password":password, "validcode":validcode}, 11 headers: {"X-CSRFToken": $.cookie("csrftoken")}, //配置csrftoken 12 success: function (data) { 13 console.log(data); 14 var response = JSON.parse(data); 15 if (response["is_login"]){ 16 self.location.href = ("/index/") 17 }else{ 18 $(".error").html(response["error_msg"]).css("color","red") 19 } 20 } 21 }) 22 }) 23 })
四、login登录函数配置
1 def login(request): 2 if request.method == "GET": 3 return render(request, "login.html") 4 elif request.method == "POST": 5 print(request.POST) 6 # 1,获取用户输入信息 7 username = request.POST.get("username") 8 password = request.POST.get("password") 9 validcode = request.POST.get("validcode") 10 session_validcode = request.session.get(‘validcode‘) 11 # 设置ajax请求的返回数据 12 login_response = {"is_login": False, "error_msg": None} 13 # 首先验证验证码输入是否正确 14 if validcode.upper() == session_validcode.upper(): 15 # 通过auth模块,验证用户名和密码是否正确 16 user = auth.authenticate(username=username, password=password) 17 print(user) 18 if user: 19 # 验证成功则在返回数据中标志True 20 login_response[‘is_login‘] = True 21 # 同时设置用户session 22 auth.login(request, user) # request.session[is_login] = True 23 else: 24 login_response[‘error_msg‘] = "用户名或密码错误" 25 else: 26 login_response[‘error_msg‘] = "验证码错误" 27 print(login_response) 28 return HttpResponse(json.dumps(login_response))
原文地址:https://www.cnblogs.com/hongdoudou/p/12635321.html
时间: 2024-10-07 01:00:57