django-simple-captcha refresh & validation

司空坚
2023-12-01

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>

 类似资料: