关闭

django-simple-captcha refresh & validation

标签: djangopythoncaptcharefreshvalidation
419人阅读 评论(0) 收藏 举报
分类:

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>


   
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:29715次
    • 积分:838
    • 等级:
    • 排名:千里之外
    • 原创:52篇
    • 转载:10篇
    • 译文:3篇
    • 评论:0条
    文章分类