Recaptcha is a free service that helps you protect your forms against spam bots by displaying a picture showing 2 words or playing an audio file telling 8 digits for the visually handicapped. After registration on http://recaptcha.net a private and a public key are generated. Put the keys in settings.py. Find client code for recaptcha at http://pypi.python.org/pypi/recaptcha-client. Put the file captcha.py into application root.
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>
`
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Absolutely brilliant. Five-minute deploy, soup to nuts.
#
Check the captcha
#
Oops - the goal of the comment above is to not use the /url/error redirect - instead this lets the user stay on the form but with the captcha redisplayed.
#
If you're using shacker's solution you'll probably want to change line 11 from:
html_captcha = captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)
to:
html_captcha = captcha.displayhtml(settings.RECAPTCHA_PUB_KEY, error=check_captcha.error_code )
This will tell the user the error if the catcha is wrong/doesn't work.
#
Absolutely brilliant!!
#
one must also need to declare html_captch as global variable, or else it doesn't work.
#
Please login first before commenting.