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

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


django-simple-captcha是django的验证码包,非常简单实用,这次记录的是如何点击验证码后刷新验证码,因为这个功能官方文档并没有详细给出。

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

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


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

2.将captcha 加入 settings.py 的 INSTALLED_APPS

3.运行 python manager.py migrations 和 python manage.py migrate,以前的版本需要用到 python manage.py syncdb

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

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

5.在forms.py中加入

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 的使用,自己学习的心得,希望能帮到更多的小伙伴。

django-simple-captcha 使用 以及添加动态ajax刷新验证的更多相关文章

  1. django-simple-captcha 验证码插件介绍 django-simple-captcha 使用 以及添加动态ajax刷新验证

    django-simple-captcha作为一款django的验证码插件,使用方法非常简单,能够快速应用到web应用中. 文档官网地址:django-simple-captcha 参考博客:http ...

  2. Django Simple Captcha插件

    正文开始 先看官方描述 1.安装 打开控制台,输入如下: pip install django-simple-captcha 2.把APP添加到Django项目进入自己的Django项目,在setti ...

  3. Django Simple Captcha的使用

    Django Simple Captcha的使用 1.下载Django Simple Captcha django-simple-captcha官方文档地址 http://django-simple- ...

  4. windows及linux下安装django simple captcha 遇到的各种问题及解决的方法

    转载自http://www.cnblogs.com/descusr/p/3225874.html 全部程序写完之后,验证码图片不显示,点击图片地址会提演示样例如以下错误,而且在linux下的纠正办法 ...

  5. Django框架 之 Form表单和Ajax上传文件

    Django框架 之 Form表单和Ajax上传文件 浏览目录 Form表单上传文件 Ajax上传文件 伪造Ajax上传文件 Form表单上传文件 html 1 2 3 4 5 6 7 <h3& ...

  6. MFC如何在树形图边上添加动态小地图

    MFC如何在树形图边上添加动态小地图 https://www.jianshu.com/p/7b1d828bf5db (简书无法识别缩进的...早知道先在博客园发了) (转载请注明出处) 作者:梦镜谷雨 ...

  7. springboot+shiro+redis(单机redis版)整合教程-续(添加动态角色权限控制)

    相关教程: 1. springboot+shiro整合教程 2. springboot+shiro+redis(单机redis版)整合教程 3. springboot+shiro+redis(集群re ...

  8. QT中添加 动态库(.so) 和 静态库 (.a) 的方法

    在QT 的Makefile文件中: 1 添加动态库,如lipcap.so 则,在LIBS一行中添加“-L/usr/local/lib -lpcap”,依据自己的情况修改libpcap.so的路径 2 ...

  9. vue微信分享链接添加动态参数

    微信分享时 分享链接携带参数可能不是固定的 需要在分享的前一刻才知道 这里就是动态设置分享链接的基本写法 代码不是那么详尽 但大致流程如下 1.安装引用jssdk npm install --save ...

随机推荐

  1. Struts2 框架的值栈

    1. OGNL 表达式 1.1 概述 OGNL(Object Graphic Navigation Language),即对象图导航语言; 所谓对象图,即以任意一个对象为根,通过OGNL可以访问与这个 ...

  2. Java 之网络编程

    网络模型 OSI 模型, 把网络通信的工作分为七层. TCP/IP 模型, 把网络通信的工作分为四层 应用层 传输层 网际层 主机至网络层 网络通信要素 (java.net 包) - IP 地址 (I ...

  3. 转!! Eclipse设定和修改文件字符编码格式和换行符

    Window -> Preferences -> General -> Workspace : Text file encoding :Default : 选择此项将设定文件为系统默 ...

  4. c#与lua交互里,错误处理

    如果是c#代码出错了 [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_down(RealStatePtr ...

  5. Redis2.8配置文件详解(转)

    add by zhj : 没找到本文的原文.另外,redis配置文件中文翻译 也翻译的不错,可以与本文对照看.两篇文章都是以Redis2.8来介绍的 在Redis中直接启动redis-server服务 ...

  6. (数据库之pymysql)

    权限管理http://www.cnblogs.com/linhaifeng/articles/7267587.html#_label6一.pymysql模块(安装与查询) 1.安装pymysql(py ...

  7. 我的Android进阶之旅------>解决Error:Unable to find method 'org.gradle.api.internal.project.ProjectInternal.g

    错误描述 今天在Github上面下载了一份代码,然后导入到Android Studio中直接报了如下图所示的错误: 错误描述如下: Error: Unable to find method 'org. ...

  8. MySQL数据库(2)- 库的操作、表的操作、数据的操作、存储引擎的介绍

    一.库的操作 1.系统数据库 执行如下命令,查看系统数据库: mysql> show databases; 参数解释: information_schema: 虚拟库,不占用磁盘空间,存储的是数 ...

  9. oracle中记录被另一个用户锁住的原因与解决办法

    oracle数据中删除数据时提示“记录被另一个用户锁住” 解决方法: 1.查看数据库锁,诊断锁的来源及类型: select object_id,session_id,locked_mode from ...

  10. Python3.x: pyodbc+FreeTDS+UinxODBC连接sybase数据库(Linux系统)

    Python3.x: pyodbc+FreeTDS+UinxODBC连接sybase数据库(Linux系统) 一.安装UinxODBC以及依赖包 yum -y install gcc gcc-c++ ...