django-simple-captcha 使用以及添加动态ajax刷新、验证
django-simple-captcha是常用的添加验证码的package,但是使用起来会遇到一些问题,比如ajax动态刷新和验证的问题,官网并没有给出详细的说明,这里做个简单的介绍。本文代码使用python3.4, django1.8,其他版本同样可以参考
django-simple-captcha 使用
- 安装 pip install django-simple-captcha, pip install Pillow
- 将captcha 加入 settings.py 的 INSTALLED_APPS
- 运行 python manager.py migrations 和 python manage.py migrate,以前的版本需要用到 python manage.py syncdb
- url路由加入urls.py的urlpatterns
urlpatterns = [
url(r'^captcha/', include('captcha.urls'))
url('^some_view/', finder.views.some_view)
]
- 在forms.py中加入
from django import forms
from captcha.fields import CaptchaField
class CaptchaTestForm(forms.Form):
title = forms.CharField(max_length=100, label='title')
price = forms.FloatField(max_value=100, label='price')
captcha = CaptchaField()
- 在views.py中加入以下代码
def some_view(request):
if request.POST:
form = CaptchaTestForm(request.POST)
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())
- template.html 的内容
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Documenttitle>
head>
<body>
<form action='.' method='POST'>
{% csrf_token %}
{{ form }}
<input type="submit" value='submit' />
form>
body>
html>
到此打开 http://localhost:8000/some_view/ 就有有一个含有验证码的title,price的表单
这里我们简单说一下验证码生成的原理,django-simple-captcha并没有使用session对验证码进行存储,而是使用了数据库,首先生成一个表 captcha_captchastore ,包含以下字段
打开http://localhost:8000/some_view/ 会发现有一个隐藏字段
这个隐藏字段就是hashkey的值,django将hashkey传给页面以hidden的形式存在,提交表单时 hashkey与 输入的验证码 一起post到服务器,此时服务器验证 captcha_captchastore表中 hashkey 对应的 response 是否与 输入的验证码一致,如果一致则正确,不一致返回错误。
django-simple-captcha ajax动态验证
了解了验证码生成的原理,我没能就可以用ajax进行动态验证
- 将一下代码写入 views.py
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:
json_data = {'status':0}
return JsonResponse(json_data)
- 写入 urls.py, 为上面的view设置路由
urlpatterns = [
url(r'^captcha/', include('captcha.urls'))
url('^some_view/', finder.views.some_view),
url('^ajax_val/', finder.views.ajax_val, name='ajax_val'),
]
- tempalte.html 写入ajax
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Documenttitle>
head>
<body>
<form action='.' method='POST'>
{% csrf_token %}
{{ form }}
<input type="submit" value='submit' />
form>
<script>
$(function(){
$('#id_captcha_1').blur(function(){
json_data={
'response':$('#id_captcha_1').val(),
'hashkey':$('#id_captcha_0').val()
}
$.getJSON('/ajax_val', json_data, function(data){
$('#captcha_status').remove()
if(data['status']){
$('#id_captcha_1').after('*验证码正确')
}else{
$('#id_captcha_1').after('*验证码错误')
}
});
});
})
script>
<script src='./jquery.js'>script> 记得导入jquery.js
body>
html>
至此我们完成了django-simple-captcha 的ajax动态验证
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/
views.captcha_refresh 源码
def captcha_refresh(request):
""" Return json with new captcha for ajax refresh request """
if not request.is_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')
通过阅读源代码我们发现, views.captcha_refresh 只接受ajax提交,最后返回 key 和 image_url 的json数据,这里的key就是 hashkey, 需要我们写入id为id_captcha_1的隐藏字段, image_url为验证码图片的新url,这里我们加入ajax刷新,点击验证码图片即可实现刷新,最新的tempalte.html 代码为
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Documenttitle>
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(){
json_data={
'response':$('#id_captcha_1').val(),
'hashkey':$('#id_captcha_0').val()
}
$.getJSON('/ajax_val', json_data, function(data){
$('#captcha_status').remove()
if(data['status']){
$('#id_captcha_1').after('*验证码正确')
}else{
$('#id_captcha_1').after('*验证码错误')
}
});
});
})
script>
<script src='./jquery.js'>script> 记得导入jquery.js
body>
html>
ok, 现在我们已经完成了对django-simple-captcha 的使用,自己学习的心得,希望能帮到更多的小伙伴。
感谢我的女朋友,她一直在身边默默的陪伴我,支持我。