Django Framework : How To Add Simple Captcha In Django Forms

Jan 23 2024 . 3 min read

In this article we are going to learn how to implement simple captch in django forms and render it to django templates. Let's implement to our form and make i more secure.

Install Dependencies

We need to install the `django-simple-captcha` dependencies first, by hitting this commdand in terminal:

pip install django-simple-captcha

Next, add captcha to the INSTALLED_APPS in your
  2.    ...
  3.    'captcha'
  4.    ...
  5. ]

Run `migrate` command

python migrate

Next, just add this path in file of the root project
  1. from django.urls import path
  2. urlpatterns = [
  3.     path("captcha/", include("captcha.urls") ),
  4. ]

Implement captcha in django form

Next, using a CaptchaField to define a captcha field:

To embed a CAPTCHA in your forms, simply add a CaptchaField to the form definition:
  1. from django import forms
  2. from captcha.fields import CaptchaField
  3. class StudentForm(forms.Form):
  4.      name = forms.CharField()
  5.      captcha = CaptchaField()

Render in template

Next, let's render the form to templates from view function.

Create view function and pass the form to context.
  1. from captcha.shortcut import render
  2. from .forms import StudentForm
  3. def student(request):
  4.      student_form = StudentForm()
  5.      return render(request, "student.html", {"student_form": student_form})

Next, simply use the form in templates file.

  1. <html>
  2.   </head>
  3.      <title> Student form <title>
  4.   </head>
  5.   </body>
  6.     </div>
  7.       {{student_form}}
  8.     </div>
  9.   </body>
  10. </html>


This is how we can use django-simple-capctha package to add the captch in our django sites to make our django form more secure.