1. view.py
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
import json
from django import forms
from captcha.fields import CaptchaField
class NameForm(forms.Form):
captcha = CaptchaField()
# Create your views here.
def get_name(request):
form = NameForm()
return render(request, 'polls/name.html',{'form':form})
def verifyCaptcha(request):
result = 'true'
_captcha_0 = request.GET.get('captcha_0') or ''
_captcha_1 = request.GET.get('captcha_1') or ''
form = NameForm({'captcha_0':_captcha_0,'captcha_1':_captcha_1})
if form.is_valid():
result = 'true'
else:
result = 'false'
return HttpResponse(json.dumps([result]), content_type='application/json')
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
# url(r'^$',view.index, name='index'),
url(r'^$', views.get_name, name='getname'),
url(r'^verifyCaptcha/$',views.verifyCaptcha, name='verifyCaptcha'),
)
<form action="." method="post" id="login-form">
{% csrf_token %}
{{form.captcha.errors}}
{{form.captcha}}
<input type="submit" value="Submit" />
</form>
<script src="{{ STATIC_URL }}js/jQuery-2.1.3.min.js"></script>
<script src="{{ STATIC_URL }}js/jquery.validate-min.js"></script>
<script type="text/javascript">
$(function(){
// refresh
$('img.captcha').click(function(){
var $form = $(this).parents('form');
var url = location.protocol + "//" + window.location.hostname + ":" + location.port + "/captcha/refresh/";
$.getJSON(url,{},function(json){
$form.find('input[name="captcha_0"]').val(json.key);
$form.find('img.captcha').attr('src',json.image_url);
});
return false;
});
// check
$("#login-form").validate({
//onfocusout:true,
//onsubmit:false,
onkeyup: false,
rules:{
captcha_1: {
// remote: '/polls/verifyCaptcha'
required: true,
remote:{
type:"get",
dataType:"json",
url:"/polls/verifyCaptcha/",
data:{
captcha_0:function(){return $("#id_captcha_0").val();}
}
}
},
},
messages:{
captcha_1:{
required:"Verification code required",
remote:"Verification code error",
}
},
invalidHandler: function(form, validator) {
//location.reload();
}
});
});
</script>