It turns out reCAPTCHA is very easy to implement 🙂
Step #1: install the Python client:
[sourcecode language=”ps”]
easy_install recaptcha-client
[/sourcecode]
Step #2: obtain public and private keys here: http://recaptcha.net/whyrecaptcha.html.
Step #3: Then create a small helper module, mycaptcha.py, for convenience and to keep your keys in one place…
[sourcecode language=”Python”]
import recaptcha.client.captcha as rc
public_key = ‘your-public-key-from-step-2-goes-here’
private_key = ‘your-private-key-from-step-2-goes-here’
def displayhtml(use_ssl=False, error=None):
return rc.displayhtml(public_key, use_ssl, error)
def submit(request):
return rc.submit(
request.REQUEST.get(‘recaptcha_challenge_field’,”),
request.REQUEST.get(‘recaptcha_response_field’,”),
private_key,
request.META.get(‘REMOTE_ADDR’, ”))
[/sourcecode]
Step #4: create your Django view
[sourcecode language=”Python”]
def captcha_test_view(request):
import mycaptcha
error = None
if request.method == ‘POST’:
response = mycaptcha.submit(request)
if response.is_valid:
return HttpResponseRedirect(‘success-url/’)
else:
error = response.error_code
recaptcha = captcha.displayhtml(error)
return render_to_response(‘recaptcha_test.html’, {‘recaptcha’:recaptcha})
[/sourcecode]
Step #5: include the following inside the form element of your html…
[sourcecode language=”Python”]
<form method=POST …>
{{ recaptcha|safe }}
…
<input type=submit>
</form>
[/sourcecode]