How to add Google reCAPTCHA to Django Form

In this Python Django tutorial, I will explain how to add Google reCAPTCHA to Django Forms step by step.

As a Python Django Developer, while working on Django Forms I want to safeguard it from spam, bots, and DDoS attacks. So, I searched for it and found that reCAPTCHA is one of the finest solutions for this.

Here we will see:

  • What is reCAPTCHA
  • How to build Django Form using Form Class
  • How to add validation on the age and number of tickets field in Django
  • Add Google reCAPTCHA to Django Forms
  • How to use various controls like textbox, email, date, time, and integer in Django
  • How to render the form as a table in Django

At the end of this article, you can also download the code: Adding Google reCAPTCHA v3 to Django Forms.

This is what we will build here.

how to add google recaptcha to django form
Add Google reCAPTCHA to Django Form

Add Google reCAPTCHA to Django Forms

Now, let us see, step by step how to create a Django form with Google reCAPTCHA.

Google reCAPTCHA

reCAPTCHA is a free service from Google that protects our website from unwanted bots or spam while submitting or passing any data through the forms.

Basically, the reCAPTCHA is a test to distinguish between humans and robots.

By including reCAPTCHA on a website, we may prevent automated software from entering while facilitating user entry. As it is simple for people to figure out but challenging for “bots” and other harmful software.

How to setup Django Google reCAPTCHA

django-recaptcha should first be installed in your activated virtual environment. With the help of this package, we can render Django forms with Google reCAPTCHA.

pip install django-recaptcha

After the installation is completed add the Django captcha to INSTALLED_APPS inside the settings.py file.

how to setup django google recaptcha
settings.py

Read: Python Django vs ReactJS

Setup Django Project with reCAPTCHA

To start a Django project, open the terminal and enter the following command. Here eBooking is the name of the Django Project.

django-admin startproject eBooking

It will make a new folder called eBooking and to enter the project type the below command in the terminal.

cd eBooking

Create a Django app named eTicket inside this project folder, by typing the below command in the terminal.

python manage.py startapp eTicket

To activate this app, add the app name to the INSTALLED_APP list located in the settings.py file.

how to setup django website with recaptcha
settings.py

Django by default includes a urls.py file in the project directory to map the newly constructed app inside of it. Add the below code in it.

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('eTicket.urls')),
]

Read: Python Django MySQL CRUD

READ:  Print Django Environment Variables

Steps to generate Google reCAPTCHA

We must generate a reCAPTCHA by following the steps below.

  1. Our website must first be registered on the reCaptcha admin console.
  2. Set label whatever we want. The label is something in a word or short phrase.
  3. We can choose any reCaptcha type you like; in this case, I have picked v2 with the “I’m not a robot” checkbox.
  4. In the Domains option, add the local host domain i.e. 127.0.0.1.
  5. Now, click on the save button to save the changes.
  6. The API keys are shown to us, upon saving the form.
python django form recaptcha
Google reCAPTCHA
django form with recaptcha
reCAPTCHA keys

Once we have obtained our API credentials, return to the Django project directory and open the settings.py file.

Now add the settings required for Django to validate reCAPTCHA as shown below.

# Recaptcha Settings
RECAPTCHA_PUBLIC_KEY = 'Paste your site key here'
RECAPTCHA_PRIVATE_KEY = 'Paste your secret key here'
SILENCED_SYSTEM_CHECKS = ['captcha.recaptcha_test_key_error']

Read: How to Create model in Django

Build Django Form using Form Class with reCAPTCHA.

To collect user input, we are using a form and we also add reCAPTCHA to it. For this, create the forms.py file and add the given code to it.

from django import forms
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV2Checkbox

# Create your forms here.

select_ticket_type = (
    ("1","VIP"),
    ("2", "Standard"),
)

class DateInput(forms.DateInput):
    input_type = 'date'

class TimeInput(forms.TimeInput):
    input_type = 'time'


class BookTicketForm(forms.Form):
    name = forms.CharField(max_length = 100)
    email = forms.EmailField()
    age = forms.IntegerField(min_value=18,max_value=50)
    ticket_type = forms.CharField(widget=forms.RadioSelect(choices=select_ticket_type))
    book_date = forms.DateTimeField(widget=DateInput)
    book_time = forms.TimeField(widget=TimeInput)
    number_of_ticket = forms.IntegerField(min_value=1,max_value=100)
    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox)

First, import the form as we create the form using the Form class.

To add the captcha to the form, import the ReCaptchaField and ReCaptchaV2Checkbox from the captcha fields and widgets, respectively.

Then create a form named BookTicketForm. And add the following fields to it.

  1. The first_name is Django CharFields. And there is a 100 max_length character limit for this character field.
  2. The email is Django EmailField which allows users to save email addresses.
  3. The age is Django IntegerField. And here we set 18 as the min_value and 100 as the max_value.
  4. The ticket_type is Django CharField. And we pass the widget attribute to it to set it as Radio Button, a choices option that are sequences that may be used as options for a field. We define a tuple for this named select_ticket_type for the option.
  5. The book_date is Django DateField and we pass the widget attribute as DateInput. And we define the DateInput class as input_type date.
  6. The book_time is Django TimeField and we pass the widget attribute as TimeInput. And we define the DateInput class as input_type time.
  7. The number_of_ticket is Django IntegerField. And here we set 1 as the min_value and 100 as the max_value.
  8. The captcha as the Django ReCaptchaField is added which will render the Google reCAPTCHA V2-Checkbox and for rendering it we pass the widget as an option to the ReCaptchaField and set its value to ReCaptchaV2Checkbox.
READ:  Python Turtle Dot - Helpful Guide

Note:

If we are using another reCAPTCHA type then the V2 Checkbox widget will be as follows.

  1. For Google reCAPTCHA V2-Invisible : ReCaptchaV2Insivible
  2. For Google reCAPTCHA V3 : ReCaptchaV3

Read: Django CRUD example with PostgreSQL

Render the form as a table in Django

In Django, the front end of the application is defined in Templates, so for this, create a subdirectory called Templates in the main project directory to store all of the project templates.

Open the settings.py file, and update the DIRS to refer to the Templates folder’s location.

build django form using form class with recaptcha
Setting Templates Folder Location

To define the front end of the Ticket Booking webpage creates an HTML file named book.html inside the Templates folder. And add the below-given code.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>E-Ticket Booking</title>
    <style>
        table {
            border: 8px outset;
            border-radius: 10px;
            border-spacing: 10px;
            padding: 20px;
            margin-left: auto;
            margin-right: auto;
        }
    </style>
</head>

<body>
    <div style="margin:80px">
        <h1 align="center">Ticket Booking Form</h1>
        <hr>
        <h3 align="center">Book your ticket directly</h3>
        <hr>
        <br>
        <form method="post">
            {% csrf_token %}
            <table>
                {{form.as_table}}
            </table>
            <br><br>
            <div style="text-align:center">
                <input type="submit" />
            </div>
        </form>
        <script src="https://www.google.com/recaptcha/api.js" async defer></script>

    </div>
</body>

</html>
  • First, we set the style of the table in the head tag.
  • Then inside the body tag, we add the heading to the form using the HTML tags h1 and h4.
  • Then call the form tag with the method POST, so the form is posted upon submission.
  • To prevent the form from cyber attacks and allow you to send the information securely, add the {% csrf_token %} within the form element.
  • Next, to render the form as a table use the form.as_tabel tag.
  • Lastly, add a submit button to submit the form.
  • To render the reCAPTCHA widget the script tag is used and this script tag consists of the source of Google reCAPTCHA API.

Note: We can include this script at any point on the HTML page without any restriction.

Read: How to build a contact form in Django using bootstrap

View Django form data on the terminal

To define the main logic for adding the Django form with reCAPTCHA, so we open the views.py file and add the below-given code.

from django.shortcuts import render
from .forms import BookTicketForm

# Create your views here.

def bookticket(request):
	if request.method == 'POST':
		form = BookTicketForm(request.POST)
		if form.is_valid():
			name = form.cleaned_data['name']
			email = form.cleaned_data['email']
			age = form.cleaned_data['age']
			ticket_type = form.cleaned_data['ticket_type']
			book_date = form.cleaned_data['book_date']
			book_time = form.cleaned_data['book_time']
			number_of_ticket = form.cleaned_data['number_of_ticket']
			print('Name:', name)
			print('Email:', email)
			print('Age:', age)	
			print('Ticket Type:',ticket_type)
			print('Book Date and Time:', book_date, book_time)
			print('Number of Tickets', number_of_ticket)      
	form = BookTicketForm()
	return render(request, "book.html", {'form':form})
  • First import the BookTicketForm from the forms.py, then call the if statement and check whether the request method is POST.
  • If yes, we pass BookTicketForm(request.POST) that binds the data to the form class, so we can do validation.
  • Call the is valid() function to check the user’s input, and if validation is successful, call the form cleaned_data[‘form field’] it validates the data and uses the print() function to display it on the terminal.
  • If the request method is GET, the user is presented with a blank book form using the render() function.
READ:  Pandas replace multiple values in Python [5 ways]

Now, we must map the view with the URL in order to call it, thus we must create a file called urls.py in the app directory. Include the code below in it.

from django.urls import path
from eTicket import views

urlpatterns = [
    path("", views.bookticket, name="bookticket"),   
]

Read: Python Django filter

Execute Ticket Booking Form Application in Django

The manage.py file for Django includes a built-in subcommand called runserver that will begin a development server for the particular Django project.

Type the below-given command in the terminal and run the server.

python manage.py runserver

It successfully opens the Django ticket booking form which looks like this.

how to add google recaptcha to django form
Form with reCAPTCHA

Now, fill out the form and click the submit button as shown below.

add google recaptcha v3 to our django forms
Online Booking with Google reCAPTCHA

After clicking on submit, it will print every attribute on the terminal.

python django form with recaptcha
Details printed on terminal

Read: Python Django group by

Download Adding Google reCAPTCHA v3 to Django Forms complete code

Here is the code:

Conclusion

With this, we have successfully created a Django Form with Google reCAPTCHA v3. We have also learned to add the validations on the form.

Additionally, we have also covered the following topics.

  • What is reCAPTCHA
  • How to build Django Form using Form Class
  • How to add validation on the age and number of tickets field
  • Add Google reCAPTCHA to Django Forms
  • How to use various controls like textbox, email, date, time, and integer in Django
  • How to render the form as a table in Django

Also, take a look at some more Python Django tutorials.