DEV Community

Cover image for Using a simple captcha in Django
Arno Pretorius
Arno Pretorius

Posted on

Using a simple captcha in Django

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 1:

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

pip install django-simple-captcha
Enter fullscreen mode Exit fullscreen mode

Step 2:
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
]
Enter fullscreen mode Exit fullscreen mode

Step 3:
Now we want to sync it to our database:

python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

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

# urls.py

urlpatterns = [
  path('captcha/', include('captcha.urls')),
]
Enter fullscreen mode Exit fullscreen mode

Step 5:
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()  
Enter fullscreen mode Exit fullscreen mode

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

<!--index.html-->

<div> {{form.captcha}} </div>
Enter fullscreen mode Exit fullscreen mode

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.


A final note…
For those that are interested in learning Django from scratch, feel free to check out my latest course:

Python Django: Ultimate Beginners Course — 2022

Top comments (0)