Django Admin框架加上DjangoCaptcha验证码

来源:互联网 发布:瓷砖效果图软件app 编辑:程序博客网 时间:2024/05/21 09:38

Django Admin框架加上DjangoCaptcha验证码

简介:本文是自己工作的总结,用Django自带的Admin框架作为后台,但是缺少验证码,故用DjangoCaptcha 给admin加上验证码。


<1>需要的东西:

DjangoCaptcha

安装:pip install DjangoCaptcha

<2>python后台代码

视图函数views.py

视图函数views.py#返回验证码图片from django.shortcuts import renderfrom django.http import HttpResponsefrom django.http import HttpResponseRedirectimport  re, jsonfrom DjangoCaptcha import Captchadef 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());



0 0
原创粉丝点击