Django and Captcha images
How to make a form with captcha imageCaptcha are images with some text that user need to write into a form field in order to send the form data. It is used as a anti-spam solutions as bots can't read text from images. In case of django/python the solution is quite easy. We can use code published by various users, for example django-captcha.
Note, that Captcha decrease site usability for people with disabilities so you should use Captcha carefully.
How does Captcha works ?- We generate a random string and place it on a temporary image
- We show that image in the form
- We make a md5 or sha1 hash out of that string and send it as a hidden field of the form or we use sessions or cookies to store it.
- When user submits the form the text he entered is hashed and compared with the original hash. If they are equal then user entered correct captcha text.
Simple Captcha with PIL
Requirements- PIL (Python imaging library)
- Simple image (a small blank banner or similar image with non aggressive background)
- A TTF font file - a bit "fantasy" font would be nice (but readable)
The CodeI used blank image called bg.jpg which I placed in the /site_media folder:
I've also placed in the same folder SHERWOOD.TTF a Baldurs Gate like font file. Next I've created a simple project and app, which returned "captcha" view under / root URL.
form.html template code: temp is a path + filename of the temporary captcha image. tempname is just the name, which is passed to the template and it is used to show the correct image. On success the view should delete the temporary image (if the user can't use the form again - for example login form)
Django Manipulator with Captcha validationFor old form system (Django <= 0.95) we can create our own Manipulators. A login form with Captcha could look like this: This code also saves captcha images in filenames based on user IP which prevents them from being overwritten by newer request (races) which in some cases can cause problems.
Bots read captchas ?Captchas aren't perfect and spammers can create tools that read text from images. Some sites use really fuzzy images but they are fuzzy also for users. A possible solution is to use a fantasy-like font which is still readable but doesn't look like a normal font.