django-simple-captcha 使用 以及添加动态ajax刷新验证

参考博客:http://blog.csdn.net/tanzuozhev/article/details/50458688?locationNum=2&fps=1css

参考博客:http://blog.csdn.net/shanliangliuxing/article/details/9214181html


 

django-simple-captcha是django的验证码包,很是简单实用,此次记录的是如何点击验证码后刷新验证码,由于这个功能官方文档并无详细给出。python

django-simple-captcha官方文档:http://django-simple-captcha.readthedocs.io/en/latest/jquery

django-simple-captcha的github网址:https://github.com/mbi/django-simple-captchagit


 

1.安装 pip install django-simple-captcha, pip install Pillowgithub

2.将captcha 加入 settings.py 的 INSTALLED_APPSajax

3.运行 python manager.py migrations 和 python manage.py migrate,之前的版本须要用到 python manage.py syncdb数据库

4.url路由加入urls.py的urlpatternsdjango

urlpatterns = [
url(r'^captcha/', include('captcha.urls')),  # 这是生成验证码的图片
url('^some_view/', finder.views.some_view),  # finder是个人app名字,须要在文件头部加入 import finder.views
]

 5.在forms.py中加入json

from django import forms
from captcha.fields import CaptchaFieldclass
class CaptchaTestForm(forms.Form):
    title = forms.CharField(max_length=100, label='title')
    price = forms.FloatField(max_value=100, label='price')  # 这里是咱们须要的字段,以title和price为例
    captcha = CaptchaField()  # 为生成的验证码图片,以及输入框

6.在views.py中加入如下代码

def some_view(request):
    if request.POST:
        form = CaptchaTestForm(request.POST)
        # Validate the form: the captcha field will automatically
        # check the input
        if form.is_valid():
            human = True
            return HttpResponse(form.cleaned_data)  # 这里没有创建模型,若是成功则直接打印
        else:
            return HttpResponse('validate error')
    else:
        form = CaptchaTestForm()
    return render_to_response('template.html',locals())  # Python 的内建函数 locals() 。它返回的字典对全部局部变量的名称与值进行映射

 7.template.html 的内容

<!DOCTYPE html>
<html lang="en">
 <head> 
  <meta charset="UTF-8" /> 
  <title>Document</title>
 </head>
 <body>
  <form action="." method="POST">
    {% csrf_token %} {{ form }}
   <input type="submit" value="submit" />
  </form>
 </body>
</html>

8.到此打开 http://localhost:8000/some_view/ 就有有一个含有验证码的title,price的表单

这里咱们简单说一下验证码生成的原理,django-simple-captcha并无使用session对验证码进行存储,而是使用了数据库,首先生成一个表 captcha_captchastore ,包含如下字段

challenge = models.CharField(blank=False, max_length=32) # 验证码大写或者数学计算好比 1+1
response = models.CharField(blank=False, max_length=32)  # 须要输入的验证码 验证码小写或数学计算的结果 好比 2
hashkey = models.CharField(blank=False, max_length=40, unique=True) # hash值
expiration = models.DateTimeField(blank=False) # 到期时间

9.打开http://localhost:8000/some_view/ 会发现有一个隐藏字段

这个隐藏字段就是hashkey的值,django将hashkey传给页面以hidden的形式存在,提交表单时 hashkey与 输入的验证码 一块儿post到服务器,此时服务器验证 captcha_captchastore表中 hashkey 对应的 response 是否与 输入的验证码一致,若是一致则正确,不一致返回错误。


 

 

10.django-simple-captcha ajax动态验证

了解了验证码生成的原理,咱们能就能够用ajax进行动态验证

将如下代码写入 views.py:

from django.http import JsonResponse
from captcha.models import CaptchaStore

def ajax_val(request):
    if  request.is_ajax():
        cs = CaptchaStore.objects.filter(response=request.GET['response'], hashkey=request.GET['hashkey'])
        if cs:
            json_data={'status':1}
        else:
            json_data = {'status':0}
        return JsonResponse(json_data)
    else:
        # raise Http404
        json_data = {'status':0}
        return JsonResponse(json_data)

11.写入 urls.py, 为上面的view设置路由

urlpatterns = [
    url(r'^captcha/', include('captcha.urls')) # 这是生成验证码的图片
    url('^some_view/', finder.views.some_view), # finder是个人app名字,须要在文件头部加入 import finder.views
    url('^ajax_val/', finder.views.ajax_val, name='ajax_val'), # 新加入
]

12.tempalte.html 写入ajax

<!DOCTYPE html>
<html lang="en">
 <head> 
  <meta charset="UTF-8" /> 
  <title>Document</title>
 </head>
 <body>
  <form action="." method="POST">
    {% csrf_token %} {{ form }}
   <input type="submit" value="submit" />
  </form> 
  <script>
    $(function(){
    $('#id_captcha_1').blur(function(){
  // #id_captcha_1为输入框的id,当该输入框失去焦点是触发函数
        json_data={
            'response':$('#id_captcha_1').val(), // 获取输入框和隐藏字段id_captcha_0的数值
            'hashkey':$('#id_captcha_0').val()
        }
        $.getJSON('/ajax_val', json_data, function(data){
 //ajax发送
            $('#captcha_status').remove()
            if(data['status']){ //status返回1为验证码正确, status返回0为验证码错误, 在输入框的后面写入提示信息
                $('#id_captcha_1').after('<span id="captcha_status" >*验证码正确</span>')
            }else{
                 $('#id_captcha_1').after('<span id="captcha_status" >*验证码错误</span>')
            }
        });
    });
    })
    </script> 
  <script src="./jquery.js"></script> 记得导入jquery.js
 </body>
</html>

 至此咱们完成了django-simple-captcha 的ajax动态验证


 

 

13.django-simple-captcha ajax刷新

若是当前验证码看不清,咱们能够刷新一下,这个咱们用ajax来作。 jango-simple-captcha自己提供了一个刷新页面,/refresh 在captcha/urls.py中:

url(r’refresh/$’, views.captcha_refresh, name=’captcha-refresh’)

这里在咱们本身的urls.py中能够不作处理,直接使用 /captcha/refresh/

14.views.captcha_refresh 源码

 

# 只是源码介绍不用写入本身的代码中
def captcha_refresh(request):
    """  Return json with new captcha for ajax refresh request """
    if not request.is_ajax():
 # 只接受ajax提交
        raise Http404
    new_key = CaptchaStore.generate_key()
    to_json_response = {
        'key': new_key,
        'image_url': captcha_image_url(new_key),
    }
    return HttpResponse(json.dumps(to_json_response), content_type='application/json')

 15.经过阅读源代码咱们发现, views.captcha_refresh 只接受ajax提交,最后返回 key 和 image_url 的json数据,这里的key就是 hashkey, 须要咱们写入id为id_captcha_1的隐藏字段, image_url为验证码图片的新url,这里咱们加入ajax刷新,点击验证码图片便可实现刷新,最新的tempalte.html 代码为

<!DOCTYPE html>
<html lang="en">
 <head> 
  <meta charset="UTF-8" /> 
  <title>Document</title>
 </head>
 <body>
  <form action="." method="POST">
    {% csrf_token %} {{ form }}
   <input type="submit" value="submit" />
  </form> 
  <script>
    $(function(){
    $('.captcha').css({
        'cursor': 'pointer'
    })
    # ajax 刷新
    $('.captcha').click(function(){
        console.log('click');
         $.getJSON("/captcha/refresh/",
                  function(result){
             $('.captcha').attr('src', result['image_url']);
             $('#id_captcha_0').val(result['key'])
          });});
    # ajax动态验证
    $('#id_captcha_1').blur(function(){
  // #id_captcha_1为输入框的id,当该输入框失去焦点是触发函数
        json_data={
            'response':$('#id_captcha_1').val(),  // 获取输入框和隐藏字段id_captcha_0的数值
            'hashkey':$('#id_captcha_0').val()
        }
        $.getJSON('/ajax_val', json_data, function(data){ //ajax发送            $('#captcha_status').remove()
            if(data['status']){ //status返回1为验证码正确, status返回0为验证码错误, 在输入框的后面写入提示信息
                $('#id_captcha_1').after('<span id="captcha_status" >*验证码正确</span>')
            }else{
                 $('#id_captcha_1').after('<span id="captcha_status" >*验证码错误</span>')
            }
        });
    });
    })
    </script> 
  <script src="./jquery.js"></script> 记得导入jquery.js
 </body>
</html>

 

ok, 如今咱们已经完成了对django-simple-captcha 的使用,本身学习的心得,但愿能帮到更多的小伙伴。

相关文章
相关标签/搜索