Django Admin框架加上DjangoCaptcha验证码

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());



发布了1 篇原创文章 · 获赞 0 · 访问量 3167

猜你喜欢

转载自blog.csdn.net/wwq_wu_hxd/article/details/43971161