(一)設(shè)置驗證碼 ?在views.py文件里定義驗證碼
#字體顏色隨機(jī)
def rndChar():
? ? return chr(random.randint(65, 90))
# 隨機(jī)顏色1:
def rndColor():
? ? return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
# 隨機(jī)顏色2:
def rndColor2():
? ? return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
def identifying(request): ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? -------------定義驗證碼
? ? width = 60 * 4 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?---------定義寬
? ? height = 60 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ---------定義高
? ? image = Image.new('RGB', (width, height), (255, 255, 255)) ? ? ?------定義一個新的圖片
? ? # 創(chuàng)建Font對象:
? ? font = ImageFont.truetype('LiberationSans-BoldItalic.ttf', 36) ? ? ? -----定義字體
? ? # 創(chuàng)建Draw對象:
? ? draw = ImageDraw.Draw(image) ? ? ? ? ? -------------------定義像素
? ? # 填充每個像素:
? ? for x in range(width):
? ? ? ? for y in range(height):
? ? ? ? ? ? draw.point((x, y), fill=rndColor())
? ? # 輸出文字:
? ? codes = ' '
? ? for t in range(4):
? ? ? ? code=rndChar()
? ? ? ? codes += code
? ? ? ? draw.text((60 * t + 10, 10), code, font=font, fill=rndColor2())
? ? # 模糊:
? ? image = image.filter(ImageFilter.BLUR)
? ? #將驗證碼字符串存儲到session中 ? ? ? ? ? ? ? ? ?---------為了判斷用戶驗證碼輸入的是否正確
? ? request.session['codes'] = codes
? ? request.session.set_expiry(0)
? ? f=BytesIO() ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? --------------圖片用字節(jié)來存儲
? ? image.save(f,'jpeg') ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?------------提交圖片
? ? return HttpResponse(f.getvalue(),'image/jpeg') ? ? ? ? ? ? ?----------獲取圖片,并定義圖片的格式
(二)在登錄的方法里驗證
#判斷驗證碼
? ? userverification=request.POST.get('identifying')
? ? codes=request.session['codes']
? ? print(codes)
? ? if userverification == None or codes.upper() != userverification.upper(): ? ? ?-----如果驗證碼為空或者不符合圖片
? ? ? ? context = {'userverification_error': '驗證碼輸入錯誤'}
? ? ? ? return render(request, 'user/login.html', context)
? ??url='/user/identifying'
? ? ? ? function checkimg(abc) {
? ? ? ? ? ? abc.src=url+'?num='+new Date()
? ? ? ? }
<img src="{%url 'user:identifying'%}" alt='驗證碼' style='cursor: pointer' onclick='checkimg(this)'>
(三)處理靜態(tài)文件
?項目中的CSS域滥、圖片、js都是靜態(tài)文件
配置靜態(tài)文件
(第一步)
在settings?文件中定義靜態(tài)內(nèi)容
STATIC_URL?=?'/static/'
STATICFILES_DIRS?=?[
????os.path.join(BASE_DIR,?'static'),
]
在項目根目錄下創(chuàng)建static目錄久橙,再創(chuàng)建當(dāng)前應(yīng)用名稱的目錄
/static/myapp/
?在模板中可以使用硬編碼
/static/my_app/myexample.jpg
?在模板中可以使用static編碼
{?%?load?static?from?staticfiles?%}
?