Adding Google reCAPTCHA v3 to your Django Forms

May 15, 2020, 12:06 p.m.

Django · 6 min read

Adding Google reCAPTCHA v3 to your Django Forms

Last Modified: Oct. 5, 2020, 2:49 p.m.

What is Google reCAPTCHA?

reCAPTCHA is a free Google service designed to protect your website from unwanted bots submitting forms.

While previous versions required some level of user interaction with "I'm not a robot" checkboxes, Google reCAPTCHA v3 tracks the interactions with your site and detects high-risk behavior.

reCAPTCHA can be added to any HTML form, but this tutorial will cover how to complete the Django Google reCAPTCHA v3 integration.

 

Django Google reCAPTCHA steps:

  1. Add domain to reCATCHA Admin Console
  2. Add reCAPTCHA keys to your Django project
  3. Add reCAPTCHA scripts to the HTML template
  4. add reCAPTCHA hidden input to the HTML template
  5. Add reCAPTCHA v3 function to Django settings
  6. Hide reCAPTCHA badge

 


 

Add a domain to Google reCAPTCHA Admin Console

Before Google reCAPTCHA can track user interaction on your site, you need to register the domain. Visit google.com/recaptcha and click on "Admin console".  Sign in with a Google account then fill out the domain registration form.

Label your reCAPTCHA something related to the Django site, click "reCAPTCHA v3", then add your website domain(s).

Localhost domains (i.e. 127.0.0.1:8000) are also accepted. 

When you are done with the form click "Submit".

Register domain

 

View your reCAPTCHA keys

Google reCAPTCHA will then generate a set of keys used to connect to your project. The first is the site key and the second is the secret key. Think of these as a username and password.

The keys can be accessed at any time in the Google reCAPTCHA Admin console under "Settings".

reCAPTCHA keys

 

Django Google reCAPTCHA v3 Integration

Add Google reCAPTCHA secret key to Django settings

env > mysite > mysite > settings.py

...

# SECURITY WARNING: keep the secret key used in production secret!
...
GOOGLE_RECAPTCHA_SECRET_KEY = 'SSSSSSSSSSSSSSSSSSSSSSSSSSS' #your reCAPTCHA secret key 

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

...

Start by adding your Google reCAPTCHA secret key, found in the Google reCAPTCHA admin console, to your settings.py file.

Make sure to place quotation marks around the secret key. We also highly recommend using Python Decouple to properly secure this secret configuration key.

 

How to add reCAPTCHA v3 in HTML template

env > mysite > main > templates > main > header.html

<!DOCTYPE html>
<html>
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
    <script src='https://www.google.com/recaptcha/api.js?render=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'></script>
  </head>
 <body>

    {% block content %}

    {% endblock %} 
      
  </body>
</html>

Then add the Google reCAPTCHA API script to your project's head element and set render equal to your reCAPTCHA site key with quotation marks only around the URL source.

If you are interested in using the Django Template Language to block content, learn how to use the Django extend template tag.

 

How to add Google reCAPTCHA script to the contact form HTML

env > mysite > main > templates > main > contact.html

{% extends "main/header.html" %}

{% block content %}

<script>
  /*global grecaptcha*/
  grecaptcha.ready(function() {
      grecaptcha.execute('AAAAAAAAAAAAAAAAAAAAAAAAAAAA', {action: "/contact/"}).then(function(token) {
        document.getElementById('g-recaptcha-response').value = token;
      });
  });
</script>



<!--Contact form-->
	...

{% endblock %}

Next, open the HTML template with your form and add the Google reCAPTCHA script to the top of the page.

For the grecaptcha.execute function, add your reCAPTCHA site key in quotes followed by the action you want to track, in this case contact.

 

Add the Google reCAPTCHA g-recaptcha-response to the Django form

env > mysite > main > templates > main > contact.html

{% extends "main/header.html" %}

{% block content %}

<script>
  /*global grecaptcha*/
  grecaptcha.ready(function() {
      grecaptcha.execute('AAAAAAAAAAAAAAAAAAAAAAAAAAAA', {action: "/contact/"}).then(function(token) {
        document.getElementById('g-recaptcha-response').value = token;
      });
  });
</script>



<!--Contact form-->
	<div style="margin:80px">
		<h1>Contact</h1>
		<h4>Contact us directly if you have any questions</h4>
		<p>
			Please write your name, email address and a message below if you have any questions.
			One of our staff members will be happy to contact you directly and answer your questions as soon as possible. 
		</p>
		<form method="post">
        {% csrf_token %}
            {{form.as_p}}
            <!--add this reCAPTCHA input-->
            <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response"> 
            <button type="submit">Submit</button>
        </form>
    </div>

{% endblock %}

Then within the form element add a hidden input element with an id and name of g-recaptcha-response for the reCAPTCHA response.

Save the changes to the file.

 

Add the g-recaptcha-response request to the Python views file

env > mysite > main > views.py

...
import json
from django.conf import settings
import urllib.request


# Create your views here.
...

def form_valid(self, form):
    # get the token submitted in the form
    recaptcha_response = self.request.POST.get('g-recaptcha-response')
    url = 'https://www.google.com/recaptcha/api/siteverify'
    payload = {
        'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
        'response': recaptcha_response
    }
    data = urllib.parse.urlencode(payload).encode()
    req = urllib.request.Request(url, data=data)

    # verify the token submitted with the form is valid
    response = urllib.request.urlopen(req)
    result = json.loads(response.read().decode())

    # result will be a dict containing 'contact' and 'action'.
    # it is important to verify both

    if (not result['contact']) or (not result['action'] == ''):  # make sure action matches the one from your template
        messages.error(self.request, 'Invalid reCAPTCHA. Please try again.')
        return super().form_invalid(form)


def contact(request):
	...

Then go to views.py and add the reCAPTCHA functionality.

First import json, settings, and urllib.request from the appropriate locations.

Then add a form_valid function that collects the hidden token in contact.html and the secret key in settings.py to post to Google's reCAPTCHA API and track the user interactions.

This form_valid function goes before the Django contact us form contact function. 

 

OPTIONAL: Hide protected by reCAPTCHA badge

{% extends "main/header.html" %}

{% block content %}

<!--Change the opacity to zero to hide the badge-->
<style>
    .grecaptcha-badge {
         opacity:0; !important;
    }
</style>

<script>
  ...
</script>


<!--Contact form-->
	<div style="margin:80px">
		<h1>Contact</h1>
		<h4>Contact us directly if you have any questions</h4>
		<p>
			Please write your name, email address and a message below if you have any questions.
			One of our staff members will be happy to contact you directly and answer your questions as soon as possible. 
		</p>
		<form method="post">
        {% csrf_token %}
            {{form.as_p}}
            <!--add the reCAPTCHA Privacy and Terms of Service disclosure-->
            <p>This site is protected by reCAPTCHA and the Google
                <a href="https://policies.google.com/privacy">Privacy Policy</a> and
                <a href="https://policies.google.com/terms">Terms of Service</a> apply.
            </p>
            <!--add this reCAPTCHA input-->
            <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response"> 
            <button type="submit">Submit</button>
        </form>
    </div>

{% endblock %}

If everything is properly configured, there will be a reCAPTCHA badge on the page where the script was added.

If you wish to hide the protected by Google reCAPTCHA badge, you can do so with the <style> element above but you are required to disclose your use of reCAPTCHA with a statement next to the form submission.

 

Add Google reCAPTCHA Terms and Conditions link

<!--Contact form-->
	<div style="margin:80px">
		<h1>Contact</h1>
		<h4>Contact us directly if you have any questions</h4>
		<p>
			Please write your name, email address and a message below if you have any questions.
			One of our staff members will be happy to contact you directly and answer your questions as soon as possible. 
		</p>
		<form method="post">
        {% csrf_token %}
            {{form.as_p}}
            <!--add the reCAPTCHA Privacy and Terms of Service disclosure-->
            <p>This site is protected by reCAPTCHA and the Google
                <a href="https://policies.google.com/terms">Terms and Conditions</a> apply.
            </p>
            <!--add this reCAPTCHA input-->
            <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response"> 
            <button type="submit">Submit</button>
        </form>
    </div>

 

Add Google reCAPTCHA Privacy Policy link

<!--Contact form-->
	<div style="margin:80px">
		<h1>Contact</h1>
		<h4>Contact us directly if you have any questions</h4>
		<p>
			Please write your name, email address and a message below if you have any questions.
			One of our staff members will be happy to contact you directly and answer your questions as soon as possible. 
		</p>
		<form method="post">
        {% csrf_token %}
            {{form.as_p}}
            <!--add the reCAPTCHA Privacy and Terms of Service disclosure-->
            <p>This site is protected by reCAPTCHA and the Google
                <a href="https://policies.google.com/privacy">Privacy Policy</a> and
                <a href="https://policies.google.com/terms">Terms and Conditions</a> apply.
            </p>
            <!--add this reCAPTCHA input-->
            <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response"> 
            <button type="submit">Submit</button>
        </form>
    </div>

 

View your site's reCAPTCHA data

To view the Google reCAPTCHA information, go to the Admin console at google.com/recaptcha/admin/.

The data is not displayed in real-time, so you will need to wait until the following day to view any information regarding the requests made on your site. 


0
Subscribe now

Subscribe to stay current on our latest articles and promos





Post a Comment
Join the community

0 Comments