django :: implementing reCAPTCHA in 5 easy steps

It turns out reCAPTCHA is very easy to implement 🙂

Step #1: install the Python client:

      easy_install recaptcha-client

Step #2: obtain public and private keys here:

Step #3: Then create a small helper module,, for convenience and to keep your keys in one place…

      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.META.get('REMOTE_ADDR', ''))

Step #4: create your Django view

      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/')
                  error = response.error_code
          recaptcha = captcha.displayhtml(error)
          return render_to_response('recaptcha_test.html', {'recaptcha':recaptcha})

Step #5: include the following inside the form element of your html…

      <form method=POST ...>
          {{ recaptcha|safe }}
          <input type=submit>
This entry was posted in django. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *