Skip to content
Related Articles

Related Articles

Improve Article

How to add Google reCAPTCHA to Django forms ?

  • Difficulty Level : Medium
  • Last Updated : 30 May, 2021
Geek Week

This tutorial explains to integrate Google’s reCaptcha system to your Django site. To create a form in Django you can check out – How to create a form using Django Forms ? 

Getting Started

Adding reCaptcha to any HTML form involves the following steps:

  1. Register your site domain to reCaptcha Admin Console.
  2. Add recaptcha keys to project settings.
  3. Add reCaptcha scripts and input element to HTML template.
  4. On form submission, make a post request to google reCaptcha API in the backend with the form’s reCaptcha field value and recaptcha keys as the POST data.
  5. Process the response from Google.

While this can be done manually, we will be using a third-party library as it makes the process much faster and simpler. Now let’s make a sample contact form where we will integrate the reCaptcha 

Initiate the Django project:

Make sure you are done with the django installation.

  • Create a new django project :
django-admin startproject dj_recaptcha
  • Create a new app say “contact” :
cd dj_recaptcha
python manage.py startapp contact
  • Go to dj_recaptcha/settings.py add the contact app.
INSTALLED_APPS = [
    ...
    'contact',
    ...
]

Registering to Google reCAPTCHA Admin Console:

First you need register your site on the reCaptcha admin console. In the domains section add 127.0.0.1 since we are testing it out locally. Later on, you can add your production URL. 



recaptcha admin console

You can specify whichever reCaptcha type you want, here we have selected v2 with ” I’m not a robot tickbox ” . You will get the API keys on form submission.

recaptcha api keys

Copy the site key and secret key into settings.py as follows:

RECAPTCHA_PUBLIC_KEY = Your_Site_Key
RECAPTCHA_PRIVATE_KEY = Your_Secret_key

As mentioned before we will be using a third-party library called django-recaptcha to make the process simpler for us. Let’s just install it now using pip, enter the following command.

pip install django-recaptcha

Add the app to the INSTALLED_APPS list in settings.py

INSTALLED_APPS = [
    ...
    'contact',
    'captcha',
    ...
]

Now let’s move on to creating a contact form in forms.py with email, feedback, and captcha as the fields.

Python3




# forms.py
  
from django import forms
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV2Checkbox
  
  
class ContactForm(forms.Form):
    email = forms.EmailField()
    feedback = forms.CharField(widget=forms.Textarea)
    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox)

The captcha field will be rendered as a checkbox field. If you specified a different type than the v2 checkbox while registering the site on recaptcha admin console, you need to change the widget attribute of ReCaptchaField above. If you don’t specify one ReCaptchaV2Checkbox will be default There are three widgets that can be used with the ReCaptchaField class:

ReCaptchaV2Checkbox for Google reCAPTCHA V2 – Checkbox



ReCaptchaV2Invisible for Google reCAPTCHA V2 – Invisible

ReCaptchaV3 for Google reCAPTCHA V3

Make an HTML template say contact.html to render the form. We will be using the default styling with {{ form.as_p }}. If you want to manually style a Django form try using widget tweaks.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <title>Contact</title>
</head>
<body>
    <h2>Contact Form</h2>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Submit</button>
    </form>
</body>
</html>

Now create a view to handle the form submission in views.py.

Python3




# views.py
from django.shortcuts import render, HttpResponse
from .forms import ContactForm
  
def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
          
        if form.is_valid():
            return HttpResponse("Yay! you are human.")
        else:
            return HttpResponse("OOPS! Bot suspected.")
            
    else:
        form = ContactForm()
          
    return render(request, 'contact.html', {'form':form})

Map the view to a URL. Here we are rendering the form on the homepage so let’s add the URL mapping for the same.

Python3




# urls.py
from django.contrib import admin
from django.urls import path
from contact import views
  
urlpatterns = [
    path('',views.contact, name='index'),
    path('admin/', admin.site.urls),
]

We are pretty much done, lets test it out by running the server and open 127.0.0.1:8000 in the browser. 

python manage.py runserver

recaptcha demo

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :