How to add reCAPTCHA in Django Site

Using Google reCAPTCHA in Django forms is one of the best way to prevent DOS attack in your Django application. Although you may deploy other measures like blocking user after 3 unsuccessful attempts or blocking the IP address but I think reCAPTCHA is one of the most widely used method to stop bots from attacking your login/sign-in page

In this Blog we will see how to use Google reCAPTCHA in Django site

What is reCAPTCHA

It is a free service from Google that helps protect websites from spam and abuse. A “CAPTCHA” is a turing test to tell human and bots apart. It is easy for humans to solve, but hard for “bots” and other malicious software to figure out. By adding CAPTCHA to a site, you can block automated software while helping your welcome users to enter with ease. Try it out at Official website.

Using reCAPTCHA

Adding re_captcha that involves some basic steps those are

1.Register site recapatcha website given below

https://www.google.com/recaptcha/admin/create

recaptcha Console

2.Put label as random like”Django_recaptcha”

3.You can specify whichever reCaptcha type you want, here we have selected v2 with ” I’m not a robot tickbox ” 

4. In the domains section add Local host Domain

       127.0.0.1

5.On Clicking on submit button Some api keys shown as shown in below screenshot Copy those

6.After completing above steps execute below command in your terminal

pip install django-recaptcha

Creating Django Project:

create a new django project :

django-admin startproject Dj_recaptcha

Create new app :

cd Dj_recaptcha
python manage.py startapp 

Go to the settings.py file and include app contact in that

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

Paste the Copied site key and secret key into settings.py as follows

RECAPTCHA_PUBLIC_KEY = 1st key
RECAPTCHA_PRIVATE_KEY = 2nd key

Let’ create forms.py file as follows

from django import forms
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV2Checkbox
  
  
class ContactForm(forms.Form):
    firstName = forms.CharField()
    LastName = forms.CharField()
    email = forms.EmailField()
    PhoneNumber = forms.IntegerField()
    Complaint = forms.CharField(widget=forms.Textarea)
    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox)

Make an HTML template say contact.html to render the form. We will be using the default styling with {{ form.as_p }}. 

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

Customize views.py file as below suggested :

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("Verification Successfull")
		else:
			return HttpResponse("Something is wrong")
			
	else:
		form = ContactForm()
		
	return render(request, 'contact.html', {'form':form})

And also Customize urls.py file in app as below

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),
]

As completing each and every steps above. we have done all let’s run the server by using below command

python manage.py runserver
Demo Video

Volia! we are successfully added Google reCAPTCHA to our django site …….

ThankYou..

GitHub link — https://github.com/saikumar248/google_reCAPTCHA.git