Table of Content
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:
Next, add captcha to the INSTALLED_APPS in your settings.py.
- INSTALLED_APPS = [
- ...
- 'captcha'
- ...
- ]
Run `migrate` command
Next, just add this path in urls.py file of the root project
- from django.urls import path
- urlpatterns = [
- path("captcha/", include("captcha.urls") ),
- ]
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:
- from django import forms
- from captcha.fields import CaptchaField
- class StudentForm(forms.Form):
- name = forms.CharField()
- 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.
- from captcha.shortcut import render
- from .forms import StudentForm
- def student(request):
- student_form = StudentForm()
- return render(request, "student.html", {"student_form": student_form})
Next, simply use the form in templates file.
- <html>
- </head>
- <title> Student form <title>
- </head>
- </body>
- </div>
- {{student_form}}
- </div>
- </body>
- </html>
Conclusion
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.