How to add Google reCAPTCHA to Django forms ? - GeeksforGeeks

30 May, 2021
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 ? 
Adding reCaptcha to any HTML form involves the following steps:
Register your site domain to reCaptcha Admin Console.Add recaptcha keys to project settings.Add reCaptcha scripts and input element to HTML template.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.Process the response from Google.
Register your site domain to reCaptcha Admin Console.
Add recaptcha keys to project settings.
Add reCaptcha scripts and input element to HTML template.
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.
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 
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',
    ...
]
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 formsfrom captcha.fields import ReCaptchaFieldfrom 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.pyfrom django.shortcuts import render, HttpResponsefrom .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.pyfrom django.contrib import adminfrom django.urls import pathfrom 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
Django-Projects
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python