django-simple-captcha refresh & validation

Preparation

Download django-simple-captcha using pip by running: pip install django-simple-captcha

Add captcha to the INSTALLED_APPS in your settings.py

Run python manage.py syncdb (or python manage.py migrate if you are managing database migrations via South) to create the required database tables
Add an entry to your urls.py:

urlpatterns += patterns('',
    url(r'^captcha/', include('captcha.urls')),
)


Django-simple-captcha 0.4.3 and later supports both Django 1.7’s new migrations and South migrations: if you are using South and Django < 1.7, you must define the following in your settings:


SOUTH_MIGRATION_MODULES = {
'captcha': 'captcha.south_migrations',
}
</pre><pre name="code" class="python"><strong><a target=_blank href="https://docs.djangoproject.com/en/1.8/intro/tutorial01">Create a app</a></strong>
</pre><pre name="code" class="python">python manage.py startapp ***
</pre><pre name="code" class="python">Add a form
***/forms.py
</pre><pre name="code" class="python">from django import forms
from captcha.fields import CaptchaField

class NameForm(forms.Form):
    captcha = CaptchaField()

 
Add urls

***/urls.py
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'),
)
Add views function
***/views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect

from .forms import NameForm

def get_name(request):
    if request.method == 'POST':
        form = NameForm(request.POST)
        if form.is_valid():
            human = True
            return HttpResponseRedirect(request.path + '?ok')
    else:
        form = NameForm()
    return render(request, 'polls/name.html',{'form':form})

Add Template file
 
***/templates/***/name.html
<form action="." method="post">
    {% csrf_token %}

    {{form.captcha.errors}}
    {{form.captcha}}
    <!--{{ form }} -->
    <input type="submit" value="Submit" />
</form>

<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    $('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;
    });
});
</script>


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值