Include captchas from recaptcha.net

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
`
# settings.py

RECAPTCHA_PUB_KEY = "your public key"
RECAPTCHA_PRIVATE_KEY = "your private key"


# urls.py

from django.conf.urls.defaults import *

urlpatterns = patterns('',
        (r'^contact/$', 'myproject.myapp.views.contact'),
)


# views.py

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django import newforms as forms
from django.conf import settings
import captcha

class ContactForm(forms.Form):
    message = forms.CharField()

def contact(request):
    if request.method == 'POST':
        # Check the captcha
        check_captcha = captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
        if check_captcha.is_valid is False:
            # Captcha is wrong show a error ...
            return HttpResponseRedirect('/url/error/')
        form = ContactForm(request.POST)
        if form.is_valid():
            # Do form processing here...
            return HttpResponseRedirect('/url/on_success/')
    else:
        form = ContactForm()
        html_captcha = captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)
    return render_to_response('contact.html', {'form': form, 'html_captcha': html_captcha})


# contact.html

<form method="post" action="">
        {{ form.as_p }}
        {{ html_captcha }}
<input type="submit" />
</form>
`

Comments

danielhepper (on March 13, 2008):

Great snippet, thanks!

For the development version, line 49 should be:

{{ html_captcha|safe }}

Otherwise autoescape will eat your captcha :)

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.