Making CAPTCHA-forms for your page

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.

Invalid CAPTCHA


Kalle Tolonen
July 6, 2022


Requirements

  1. A basic understanding of object oriented programming
  2. A working Django-project with forms
  3. Being comfortable with Django

Tested on
- Django 3.2
- Debian 11

Installation

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

Add to settings

To make our new package available for use, we need to add it to our settings.py.

#settings.py additions

INSTALLED_APPS = [
    'captcha',
]

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... OK

Urls

Next, let’s make additions to urls.py.

#urls.py

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

Usiong CAPTCHA in your app

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)

Views

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

Sources and further reading

  1. https://en.wikipedia.org/wiki/CAPTCHA
  2. https://django-simple-captcha.readthedocs.io/en/latest/usage.html

Comments

No published comments yet.

Add a comment

Your comment may be published.