Django Admin框架加上DjangoCaptcha驗證碼
簡介:本文是自己工作的總結,用Django自帶的Admin框架作爲後臺,但是缺少驗證碼,故用DjangoCaptcha 給admin加上驗證碼。
<1>需要的東西:
DjangoCaptcha
安裝:pip install DjangoCaptcha
<2>python後臺代碼
視圖函數views.py
視圖函數views.py
#返回驗證碼圖片
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
import re, json
from DjangoCaptcha import Captcha
def code(request):
ca = Captcha(request)
#ca.words = ['hello','world','helloworld']
ca.img_width = 150
ca.img_height = 30
#ca.type = 'number'
ca.type = 'word'
return ca.display()
#驗證,提交的驗證碼是否正確
def verifyAjax(request):
result = 'false'
_code = request.GET.get('code') or ''
if not _code:
return HttpResponse(json.dumps([result]), content_type='application/json')
ca = Captcha(request)
if ca.check(_code):
result = 'true'
else:
result = 'false'
return HttpResponse(json.dumps([result]), content_type='application/json')
<3>html顯示驗證碼
<a href="#" id="get_code_img"><img src="/accounts/verify/code" class="getcode" /></a>
<input type = "text", id = "captcha_input", name = "captcha_input">
<4>js 代碼表單驗證
這裏我們使用jQuery 的validate 框架的異步驗證
//驗證表單
$("#login-form").validate({
rules:{
captcha_input:{
required:true,
remote:{
url:'/accounts/verify/verifyAjax',
type:'get',
dataType:'json',
data:{
code:function(){
return $("#captcha_input").val();
},
},
}
}
},
messages:{
captcha_input:{
required:"Verification code required",
remote:"Verification code error",
}
},
//未驗證時回調
invalidHandler: function(form, validator) {
//location.reload();
}
});
//刷新驗證碼
$("#get_code_img").click(function() {
$(".getcode").attr("src", "/accounts/verify/code?rand=" + Math.random());
return false;
});
$(".getcode").attr("src", "/accounts/verify/code?rand=" + Math.random());