安裝圖片處理模塊pillow : pip install pillowjavascript
pillow官網:http://pillow.readthedocs.io/en/latest/css
在views.py添加視圖java
#驗證碼 from django.http import HttpResponse def verifyCode(request): # 引入繪圖模塊 from PIL import Image, ImageDraw, ImageFont # 引入隨機函數模塊 import random # 定義變量,用於畫面的背景色、寬、高 bgcolor = (random.randrange(20, 100), random.randrange( 20, 100), 255) width = 100 height = 25 # 建立畫面對象 im = Image.new('RGB', (width, height), bgcolor) # 建立畫筆對象 draw = ImageDraw.Draw(im) # 調用畫筆的point()函數繪製噪點 for i in range(0, 100): xy = (random.randrange(0, width), random.randrange(0, height)) fill = (random.randrange(0, 255), 255, random.randrange(0, 255)) draw.point(xy, fill=fill) # 定義驗證碼的備選值 str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0' # 隨機選取4個值做爲驗證碼 rand_str = '' for i in range(0, 4): rand_str += str1[random.randrange(0, len(str1))] # 構造字體對象 font = ImageFont.truetype('Arial.ttf', 23) # 構造字體顏色 fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255)) # 繪製4個字 draw.text((5, 2), rand_str[0], font=font, fill=fontcolor) draw.text((25, 2), rand_str[1], font=font, fill=fontcolor) draw.text((50, 2), rand_str[2], font=font, fill=fontcolor) draw.text((75, 2), rand_str[3], font=font, fill=fontcolor) # 釋放畫筆 del draw # 存入session,用於作進一步驗證 request.session['verifycode'] = rand_str # 內存文件操做 #import cStringIO python 2的用法 #buf = cStringIO.StringIO() #buf = io.StringIO() import io #從Python 3.0開始,StringIO和cStringIO模塊已經取消。經過import io模塊代替 buf = io.BytesIO() # 將圖片保存在內存中,文件類型爲png im.save(buf, 'png') # 將內存中的圖片數據返回給客戶端,MIME類型爲圖片png return HttpResponse(buf.getvalue(), 'image/png')
若報錯OSError cannot open resource 沒有此字體python
能夠去本身的python目錄下搜索ttf 而後替換爲本身的絕對路徑 例:C:/Users/Administrator/font/Arial.ttfjquery
效果django
========================================================================================session
配置urldom
path('verifyCode/',views.verifyCode)函數
頁面顯示驗證碼 src指向驗證碼urlpost
<img id='verifyCode/' src="/verifyCode/" alt="CheckCode"/>
<script type="text/javascript" src="/static/jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(function(){ $('#verifycodeChange').css('cursor','pointer').click(function() { $('#verifyCode').attr('src',$('#verifyCode').attr('src')+1) }); }); </script> <img id='verifyCode' src="/verifyCode/?1" alt="CheckCode"/> <span id='verifycodeChange'>看不清,換一個</span>
<form method='post' action='/verifycodeValid/'>
{%csrf_token%} <input type="text" name="vc"> <img id='verifyCode' src="/verifyCode/?1" alt="CheckCode"/> <span id='verifycodeChange'>看不清,換一個</span> <br> <input type="submit" value="提交"> </form>
from django.http import HttpResponse def verifycodeValid(request): vc = request.POST['vc'] if vc.upper() == request.session['verifycode']: return HttpResponse('ok') else: return HttpResponse('no')
urlpatterns = [
path('verifycodeValid/',views.verifycodeValid),
]
若報錯403
在模板中,在表單Form裏須要有{%csrf_token%}(模板網址標記在每一個郵局形式的內部目標)。