In this tutorial, I will show you how to implement google recaptcha v3 into your django app.

I also already create a simple django app, and what we will do here only to integrate the google recaptcha v3 in some views.

Let’s get started.

Clone App

Clone https://github.com/ihfazhillah/django-recaptchav3-example , then optionally create a virtualenv. Install the dependency.

FYI, the repo has 2 branches. master and final . Just start with master branch, and you can get the final result in the final branch.

Step 1: Register Google Recaptcha and Choose v3

Go to https://g.co/recaptcha/v3 , then create a new site.

Insert your Label, choose reCaptcha v3 in the recaptcha type.

Add localhost and 127.0.0.1 into domains field for local testing.

Accept the TOS. And then click submit.

You will see secret key and site key . The site key is what you need to implement google recaptcha v3 in the frontend. And secret key, keep it secret. This will be used for g-recaptcha's frontend response verification on your backend.

Step 2: Put Keys Into settings.py

Grab secret_key and site_key into settings.py like this:

and add site key into your index view

Step 3: Implement g-recaptcha on your frontend

open templates/index.html and add this javascript script:

Use jquery to work with selector. It will make selection easier. Render the recaptcha v3 in your page when recaptcha ready, then when user click on submit button, execute grecaptcha to get the response token include the response token into form request and we will verify it on the backend

and add this hidden input in the form

now recaptcha activated !

Step 4: Implement g-recaptcha verification on your backend

open recaptcha_example/views.py and write down this on the contact view function:

Get recaptcha response token from frontend. verify it if success true we can assumse that the user is not a robot, and process whole request if not, return error. Don’t forget to install requests package

If you curious, this is example of response from g-recaptcha verification

and I’m not a robot. Yay…

Conclusion

That’s all. We use google recaptcha v3, so there are no interruption to our visitor and we will get a score between 0.0 into 1.0 to indicate the visitor is a robot or human.

Thanks for reading, and hope you can implement it into your next project.