How To Integrate Or Use Google Recaptcha In Django Forms

This tutorial explains how to integrate Google’s reCaptcha system to your Django site. In this article we are going to see the ways you can make google recaptcha a required field and also the way you can add it to backend

You can check thedocumentation here; you can also reffer to this posts below if you don’t know how to start a project.

How to create and run a web app on pythonanywhere

how-to-host-a-website-on-pythonanywhere

how-to-deploy-your-project-on-github-using-termux-and-android

Steps required to use Google recaptcha in Django forms

  • Register your site domain to reCaptcha Admin Console.
  • Add recaptcha keys to project settings.
  • Add reCaptcha scripts and input element to HTML template.
  • Add recaptcha form to form.py to make a required field
  • Process the response from Google.
  • Also add css and JavaScript so as to make it a required field if you are not using it in forms.py

Illusstration of how to use google reCaptcha in login or signin forms
Assuming that we have a project named benchatronics and an app named benny. And we have mapped our url even tologin.htmlprocess.

Registering to Google reCAPTCHA Admin Console:
First you need toregisteryour site on the reCaptcha admin console. In the domains section add127.0.0.1since we are testing it out locally. Later on, you can add your production URL.
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, select all that applies to complete the signup; Copy your secret key and Id you would be adding them to settings.py soon

After you have registered with google reCaptcha, go to your settings.py in the project folder, add the keys to your settings.py as i have I added below then replace them with your own keys and secret id.

install this by running the command

pip install django-recaptcha
<br>#recaptcha<br>RECAPTCHA_PUBLIC_KEY = '6LdvWlMhAAAAAPHGUHFYHLfW6NUYzuxmNpk'<br>RECAPTCHA_PRIVATE_KEY = '6LdAAHdvVSJSBEJEJHjxNR5OnXOLNjmHDh9szh'<br>#recapta ends here<br>


Add reCaptcha to your installed apps.


INSTALLED_APPS = [
    'posts',
    'captcha',
]

Now we are set to add reCaptcha to our signin page using javascript and css.In your login.html add these google api code.
Add these google api before </head> in your login.html form

 <script src="https://www.google.com/recaptcha/api.js" <strong>async</strong> defer></script>

Google recaptcha
Now let’s make a sample contact form where we will integrate the reCaptcha.

Add the code below in the login.html code. Remember you are to add it where you want it to appear so that your visitors can click it.

For this post i have added it before the submit button

 <div <strong>class</strong>="g-recaptcha" data-sitekey="REPLACE WITH-YOUR-OWN-DATA-SITE-KEY"></div>
      

Note: You are to add the code above to your login form.add it where ever you want it to appear.

lets check by running

python manage.py makemigrations
python manage.py migrate
python manage.py runserver
recaptcha



Now there is one draw back in the method above . The google reCaptcha is not a required field one can skip at any time .

To make it a required field let’s add css and javascript.

Illustration ofhow to add javascript to make google reCaptcha a required field
At the bottom before </body add these code below


      <script type="text/javascript"> window.onload = <strong>function</strong>() {
    <strong>var</strong> $recaptcha = document.<strong>querySelector</strong>('#g-recaptcha-response');

    <strong>if</strong>($recaptcha) {
        $recaptcha.<strong>setAttribute</strong>("required", "required");
    }
};</script>


Now add this css to your style.css


 #g-recaptcha-response {
    <strong>display</strong>: block !important;
    <strong>position</strong>: absolute;
    <strong>margin</strong>: -78px 0 0 0 !important;
    <strong>width</strong>: 302px !important;
    <strong>height</strong>: 76px !important;
    <strong>z-index</strong>: -999999;
    <strong>opacity</strong>: 0;
}

Refresh the page and try to signin without ticking the reCaptcha you will see that it will tell you that you must fill it.

Google recatcha



This is not the most efficient way of adding reCaptcha in django because it can still be overided by hackers , there in the next paragraph we would be adding it in our form.py to illustrate how to add recaptcha in Django signup forms.

Illustration of how to Use recaptcha in forms.py

In benchatronics/benny/forms.py Import this code on the top.

<strong>from</strong> .models <strong>import</strong> *
<strong>from</strong> django <strong>import</strong> forms
<strong>from</strong> django.contrib.auth.models <strong>import</strong> User
<strong>from</strong> django.contrib.auth.forms <strong>import</strong> UserChangeForm,PasswordChangeForm,UserCreationForm
<strong>from</strong> captcha.fields <strong>import</strong> ReCaptchaField
<strong>from</strong> captcha.widgets <strong>import</strong> ReCaptchaV2Checkbox
#########################

After importing all these edit your forms.py so that it looks like the one below

<strong>from</strong> .models <strong>import</strong> *
<strong>from</strong> django <strong>import</strong> forms
#from django.forms import ModelForm
<strong>from</strong> django.contrib.auth.models <strong>import</strong> User
<strong>from</strong> django.contrib.auth.forms <strong>import</strong> UserChangeForm,PasswordChangeForm,UserCreationForm
<strong>from</strong> captcha.fields <strong>import</strong> ReCaptchaField
<strong>from</strong> captcha.widgets <strong>import</strong> ReCaptchaV2Checkbox
#########################

<strong>class</strong> <strong>SignUpForm</strong>(<strong>UserCreationForm</strong>):
    first_name = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'class':'form-control'}))
    last_name = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'class':'form-control'}))
    email = forms.EmailField(widget=forms.EmailInput(attrs={ 'class':'form-control'}))
    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox)

    <strong>class</strong> <strong>Meta</strong>:
        model = User
        fields = ('username','first_name','last_name','email','captcha')

    <strong>def</strong> <strong>__init__</strong>(self,*args,**kwargs):
        super(SignUpForm,self).__init__(*args,**kwargs)
        self.fields['username'].widget.attrs['class']='form-control'
        self.fields['password1'].widget.attrs['class']='form-control'
        self.fields['password2'].widget.attrs['class']='form-control'


Now head over to benchatronics/templates/signup.html and add this code.

{% extends 'main.html' %}
{% block title %} Register | benchatronics {% endblock %}

{% block detail %}
         <!-- Page header with logo and tagline-->
        <<strong>header</strong> class="py-5 bg-success border-bottom mb-4">
            <<strong>div</strong> class="container">
                <<strong>div</strong> class="text-center my-5">
                    <<strong>h1</strong> class="fw-bolder text-white">SignUp for Benchatronics</<strong>h1</strong>>
                    <<strong>p</strong> class="lead mb-0"></<strong>p</strong>>
                </<strong>div</strong>>
            </<strong>div</strong>>
        </<strong>header</strong>>
        {% endblock %}

{% load static %}

{% block content %}
{% if user.is_authenticated %}
<<strong>p</strong>>You are logged in </<strong>p</strong>>
{% else %}
<<strong>div</strong> class="container shadow rounded p-4 mb-5 bg-body">
<<strong>form</strong> method="post" action="{% url 'signup' %}">

    <<strong>div</strong> class="m-2 container ">
    {% csrf_token %}

    {{form.as_p}}
    <<strong>button</strong> class="btn btn-primary" type="submit" >REGISTER</<strong>button</strong>>
    </<strong>div</strong>>
</<strong>form</strong>>
</<strong>div</strong>>
{% endif  %}
{% endblock content %}


Head over to your views.py then add this code

<strong>from</strong> . forms <strong>import</strong> *
<strong>from</strong> django.contrib.auth.models <strong>import</strong> User,auth
<strong>from</strong> django.contrib <strong>import</strong> messages
<strong>from</strong> . models <strong>import</strong> *
<strong>from</strong> django.db.models <strong>import</strong> Q
<strong>from</strong> django.contrib.auth <strong>import</strong> authenticate,login





<strong>def</strong> <strong>signup</strong>(request):
    <strong>if</strong> request.method == 'POST':
        form = SignUpForm(request.POST)
        <strong>if</strong> form.is_valid():
            form.save()
            username = form.cleaned_data['username']
            password1 = form.cleaned_data['password1']
            user = authenticate(username=username,password=password1)
            auth.login(request,user)
            messages.success(request,("You have successfully login"))
            <strong>return</strong> redirect('/')
    <strong>else</strong>:
        form = SignUpForm
    <strong>return</strong> render(request, 'signup.html',{'form':form})

Now head over to benchatronics/benny/urls.py and add this urls mapping .

#add this to your urls.py

path('signup',views.signup, name='signup'),
    ]



Now head over to your terminal after saving all your project and run python manage.py runserver to check our instances on signup.html;

signup forms

Conclusion: We added a simple Recaptcha in our sign in form but it was not a required field therefore we added recaptcha in our forms.py making it a required field. I have tested this project before uploading codes and it worked very well for me so if anything is wrong you can leave a comment below.

The best way of adding recaptcha is to add it to the backend as we have done it above.

Leave a Reply

Your email address will not be published. Required fields are marked *