Making Captcha in Django

By Samuel Muiruri | Dec. 20, 2018 | Django

Here’s how you can make a Captcha in Django, working, Github repo. Use the following to log in.

Using bootstrap 4.4 and latest version of jQuery and jquery.cookie to read and write cookies… and the login page with a basic form and javascript for handling the form request.

The javascript, jQuery code for parsing the ajax request for logging in looks like this

What the captcha does is generate an equation and draws it on an image to make it harder for a bot to get the content and then log’s in the user if successful.

The views has a few things that happen together for a the process of logging in the user. First there’s a function that creates a random file name for the image captcha created.

and wrapped in a single function generate captcha that randomly generates an equation like 50-2 returns all the relevant info related to it like, the image url and saves the image so you don’t make duplicate images for the same equation.

Then with a few lines the login page loads with a random captcha ready for username, password and the answer to the question.

Now the user types the right stuff and presses enter and then ajax post is dealt with this which reads the json data, checks to see if the captcha then username, password match. If all three pass using django inbuilt login the user is logged in and then the js gets status == 'ok and redirects to \admin\ .

And that’s it!

Here's the final result

The captcha is an image

which means without an Object Character Recognition script that can parse text from an image a basic script won't be able to get over this.