Integrating Google Recaptcha to Django
Like many, I hate captchas. They are tedius and put the burden on your real users to prove they are real. I prefer whenever possible to try to implement a honeypot anti-spam layer. Recently, however I had a site with public forms that a honeypot wasn’t doing an adequate job of protecting.
I recently decided to try out Google’s checkbox recaptcha and I’m not unhappy with it.
How does it work?
At a very basic level, there is a block of html containing your public key that you add to your html form. A google hosted JS script hijacks and makes the html block into a recaptcha element. When a person checks the checkbox, the JS reaches out to the recaptcha service and retrieves a one-time token that gets submitted with the form via a hidden field.
In your backend code, you take the token and a secret key provided to you at signup and then send them to the service API URL via a post. The service API returns a JSON string representing success or failure. Based on the success or failure of this API call, validate the form appropriately.
How to integrate into Django
Add some settings to your Django project. You want these credentials to be managed at an environment level and not embedded in your code.
Create a context processor. The point of this context processor is to make the public key,
GOOGLE_RECAPTCHA_SITE_KEY, available to your template system.
context_processors.py file to your app’s folder if you do not already have one and add the following function.
Next, tell your site to use this Context. In your site’s settings file add
'contact.context_processors.recaptcha' to the
Now that your public key is available in your templates, add the recaptcha html element to your forms before the submit button and closing
Add Google’s script before your closing
</head> tag per their instructions.
Django Forms work
Your form will need access to the request object in order to send some optional information to the service. So, in your view pass the request obect into the form as a keyword argument.
Then, in your form test the recaptcha token and user’s IP against the recaptcha serice by utilizing the request object that you passed to the form in the step above.