您好,登錄后才能下訂單哦!
應用下創(chuàng)建untils文件夾放置封裝圖片驗證碼的函數(shù)
創(chuàng)建validCode.py文件定義驗證碼規(guī)則
import random def get_random_color(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) def get_valid_code_img(request): # 方式: from PIL import Image, ImageDraw, ImageFont from io import BytesIO import random img = Image.new("RGB", (270, 40), color=get_random_color())#生成一個寬270*高40的畫布,背景顏色隨機 draw = ImageDraw.Draw(img)#進行繪畫 kumo_font = ImageFont.truetype("static/font/kumo.ttf", size=32)#字體 字體大小 valid_code_str = "" for i in range(5): random_num = str(random.randint(0, 9))#0-9的隨機數(shù) 9 random_low_alpha = chr(random.randint(97, 122))#a 到 z 隨機的一個小寫字母 b random_upper_alpha = chr(random.randint(65, 90))#A 到 Z 隨機的一個大寫字母 Q random_char = random.choice([random_num, random_low_alpha, random_upper_alpha]) #2 draw.text((i * 50 + 20, 5), random_char, get_random_color(), font=kumo_font) #往長方形上寫字 # 保存驗證碼字符串 valid_code_str += random_char #85656 width=270 height=40 for i in range(10): # draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color())#畫小點 x = random.randint(0, width) y = random.randint(0, height) draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color()) #小線段 request.session["valid_code_str"] = valid_code_str f = BytesIO() img.save(f, "png") #png data = f.getvalue() return data
建路由
# 登錄 path('login/', login.login,name='login'), # 圖片驗證碼 re_path('get_valid_code_img/', login.get_valid_code_img, name='get_valid_code_img'),
寫后臺方法
from blog.utils import validCode # 引入自定義的驗證碼 #頁面返回方法 from django.shortcuts import render, HttpResponse, redirect #哈希加密 from django.contrib.auth.hashers import make_password, check_password #數(shù)據(jù)庫 from blog.models import Article, Comment, Member, Praise, Web, Image # 登陸 def login(request): res = {'status': None, 'info': None} if request.method == 'POST': valid_code = request.POST.get("valid_code") valid_code_str = request.session.get("valid_code_str") print(valid_code, valid_code_str) if valid_code.upper() == valid_code_str.upper(): # 查詢用戶和密碼是否正確 username = request.POST.get('username') pwd = request.POST.get('pwd') username_obj = Member.objects.filter(member_name=username).first() if not username_obj: res['status'] = 3 res['info'] = '用戶名不存在' return HttpResponse(json.dumps(res)) if check_password(pwd, username_obj.member_pwd): res['status'] = 1 res['info'] = '登錄成功' request.session['member_name'] = username request.session['member_id'] = Member.objects.filter(member_name=username).first().member_id response_new = HttpResponse(json.dumps(res)) # 把這個結(jié)果告訴給前臺,ajax return response_new else: res['status'] = 0 res['info'] = '帳號/密碼錯誤' return HttpResponse(json.dumps(res)) else: res['status'] = 2 res['info'] = '驗證碼錯誤' return HttpResponse(json.dumps(res)) return render(request, 'blog/login.html', locals()) # 生成圖片驗證碼 def get_valid_code_img(request): img_data = validCode.get_valid_code_img(request) return HttpResponse(img_data)
前端登錄的表單
{#登陸的表單#} <form action="{% url 'blog:login' %}" method="post" id="login"> <input type="text" class="name" name="username" Placeholder="Username" required=""/> <input type="password" class="password" name="pwd" Placeholder="Password" required=""/> {% csrf_token %} <input type="text" name="valid_code" placeholder="驗證碼"> <img width="270" height="36" id="valid_code_img" src="/blog/get_valid_code_img/" onclick="this.src='/blog/get_valid_code_img/?'+Math.random()"> <div class="login-agileits-bottom"> <h7><a href="javascript:;" type="button" id="onsubmit">登陸</a></h7> </div> </form> {#登陸的表單結(jié)束#}
前端提交登錄表單的jquery
{# 登陸的jquery #} $(document).ready(function () { $('#onsubmit').click(function () { $.post('/blog/login/', $('#login').serialize(), function (data) { if (data['status'] == 1) { layer.msg(data.info); location.href = "{% url 'index' %}"; } else { layer.msg(data['info']) } }, 'json') }) }) {# 登陸的jquery結(jié)束 #}
頁面效果
總結(jié)
以上所述是小編給大家介紹的django項目登錄中使用圖片驗證碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。