How to add a security captcha with a "I am not a robot" for a django project ?

Published: August 21, 2023

Tags: Django; Captcha;

DMCA.com Protection Status

To add a security captcha to your Django project, there are several different methods you can use. One of the most popular is using Google's “I am not a robot” CAPTCHA. This type of captcha requires users to click on a checkbox to confirm that they are human before submitting any information.

Google reCAPTCHA

I created a contact form using Django, but it's been receiving a lot of spam messages. I'm looking for a solution to filter out the spam quickly and easily. One possible solution I've found is to use Google reCaptcha, which adds a security checkbox (like the example below) to the contact form.

How to add a security captcha with a
How to add a security captcha with a "I am not a robot" for a django project ?

To start using Google reCaptcha, first, go to the reCaptcha page.

How to add a security captcha with a
How to add a security captcha with a "I am not a robot" for a django project ?

Next, click on the "v3 Admin Console" button located in the top navigation bar. You will be directed to a new page where you can register a new site (refer to the image below). Select a label that represents the site (such as ContactForm) and enter the site's domain name. Afterward, accept the Terms of Service and click on the submit button.

Note: to test the captcha locally with a django project, add either "127.0.0.1" or "localhost" to the Google domain name.

How to add a security captcha with a
How to add a security captcha with a "I am not a robot" for a django project ?

Once you have completed the registration process, Google will provide you with two pieces of information: a site key and a secret key. You will need to add these keys to your Django project’s settings file in order for the captcha to function correctly.

How to add a security captcha with a
How to add a security captcha with a "I am not a robot" for a django project ?

Django project

Now, et's update the Django project now that we have both a public and a secret key.

Edit settings.py file

GOOGLE_RECAPTCHA_SECRET_KEY = '****************'

Create a template with a contact form

The next step is to add the captcha code into your HTML form. First, you will need to include the Google reCAPTCHA JavaScript API into your form template. This is done by adding the following line of code into your HTML template:

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

Then, you will need to add the actual captcha widget itself. This is done by adding the following line of code:

<div class="g-recaptcha" data-sitekey="***************"></div>

<form action="/Contact-US/" method="post">

{% csrf_token %}

<input type="text" name="subject">

<textarea name="content" rows="20"></textarea>

<script src='https://www.google.com/recaptcha/api.js'></script>

 <div class="col-md-12">
     <div class="g-recaptcha" data-sitekey="public_key_here"></div>
 </div>

<input type="submit" value="Send your message">

</form>

Create a view

Finally, you can add the code that will validate the captcha. This is done by adding the following line of code into your form’s view, example:

import urllib

def Message_Create_View(request):
    contact_form = Contact_Form()
    if request.method == 'POST':
        form = Contact_Form(request.POST)
        if form.is_valid():
            #----- form -----#
            subject = request.POST['subject']
            content = request.POST['content']
            name = request.POST['name']
            email = request.POST['email']
            recaptcha_response = request.POST.get('g-recaptcha-response')
            #---- captcha -----#
            url = 'https://www.google.com/recaptcha/api/siteverify'
            values = {
                'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
                'response': recaptcha_response
            }
            data = urllib.parse.urlencode(values).encode()
            req =  urllib.request.Request(url, data=data)
            response = urllib.request.urlopen(req)
            result = json.loads(response.read().decode())
            #---- process data  -----#
            if result['success']: # if captcha is successful
                # do soemthing
            else:
                # do soemthing              
    context = {'contact_form':contact_form}
    return render(request, "my_app/Contact.html", context)

Now that you have added the necessary code to your project, users should now be able to verify they are not robots and complete their form submission. Adding a security captcha can help protect your website from malicious bots, ensuring your user's data is safe and secure.

References

Links Site
recaptcha google
Image

of