In this article, I'll show you how you can implement CAPTCHA's for yourself. CAPTCHA's are easy to figure out for humans, but harder for bots, so they're a widespread way of protecting online forms from abuse.

Kalle Tolonen
July 6, 2022
Tested on
- Django 3.2
- Debian 11
First you should add the pkg to you requirements.txt and install it.
#requirements.txt
pillow
django-simple-captcha
The you can install it with pip. Make sure you’re within you environment for this.
which pip
(env)$ which pip
/home/user/projecttop/env/bin/pip
After making sure, you can install the package.
pip install -r requirements.txt
To make our new package available for use, we need to add it to our settings.py.
After this, you have to run migrations.
./manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, captcha, contenttypes, list, mainsite, sessions
Running migrations:
Applying captcha.0001_initial... OK
Applying captcha.0002_alter_captchastore_id... OKNext, let’s make additions to urls.py.
Adding the functionality to a form is done easily by modifying your form.
from django import forms
from captcha.fields import CaptchaField
class ContactForm(forms.Form):
captcha = CaptchaField()
name = forms.CharField(max_length = 50)
email = forms.EmailField(max_length = 150)
message = forms.CharField(widget = forms.Textarea, max_length = 2000)To make things visible, we need to modify our views.
#views.py
def contactform(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
human = True
name = form.cleaned_data['name'],
subject = f"Contact form inquiry: { name }"
body = {
'name': form.cleaned_data['name'],
'email': form.cleaned_data['email'],
'message':form.cleaned_data['message'],
}
message = "\n".join(body.values())
try:
send_mail(subject, message, 'sender@example.com', ['receiver@example.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect ("thanks")
else:
form = ContactForm()
return render(request, "mytemplate.html", {'form':form})So, there we have it, a working CAPTCHA contact form to hinder some of the spam :)
No published comments yet.
Your comment may be published.