Using a simple captcha in Django

Integrating a simple captcha form into your Django web application.

*This part requires you to have sufficient knowledge of Django forms.*


A CAPTCHA is a response check to test if the user is a robot or a human. This is particularly effective in deterring hackers from using bot software to submit fake or malicious online requests through our application.


There are many packages available for CAPTCHA, but I would suggest that you use django-simple-captcha, simply because it is so ‘simple’ to set up.


Step one:

To install django-simple-captcha, open up your terminal and type in the following command:


pip install django-simple-captcha


Step two:

Next, you want to add ‘captcha’ under your installed apps. The position is irrelevant here, so insert it anywhere that you want.


# settings.py

INSTALLED_APPS = [
    'captcha', # Captcha
]

Step three:

Now we want to sync it to our database:


python manage.py migrate

Step four:

We now need to add our captcha to our urls.py file:


# urls.py

urlpatterns = [
  path('captcha/', include('captcha.urls')),
]

Step five:

You need to embed CAPTCHA into your Django form. For example, it could be done like so:


# forms.py

from django import forms
from captcha.fields import CaptchaField 

class TestForm(forms.Form):
   my_firstName = OtherField()
   my_lastName = OtherField()

   captcha = CaptchaField()  

Step six:

An example of how this could be implemented in your HTML form:


<!--index.html-->

<div> {{form.captcha}} </div>

DONE!

That's how to implement a simple captcha into your Django web application. This will help to maintain the integrity of your user forms by preventing bots from sending requests.