from django.shortcuts import render_to_response from os import remove def captcha ( request ): # random generator from random import choice # PIL elements, sha for hash import Image , ImageDraw , ImageFont , sha # create a 5 char random strin and sha hash it, note that there is no big i SALT = settings . SECRET_KEY [: 20 ] imgtext = '' . join ([ choice ( 'QWERTYUOPASDFGHJKLZXCVBNM' ) for i in range ( 5 )]) # create hash imghash = sha . new ( SALT + imgtext ) . hexdigest () # create an image with the string (media is the folder with static files accessed by /site_media) # PIL "code" - open image, add text using font, save as new im = Image . open ( 'media/bg.jpg' ) draw = ImageDraw . Draw ( im ) font = ImageFont . truetype ( 'media/SHERWOOD.TTF' , 18 ) draw . text (( 10 , 10 ), imgtext , font = font , fill = ( 100 , 100 , 50 )) # save as a temporary image # I use user IP for the filename, SITE_IMAGES_DIR_PATH - system path to folder for images temp = settings . SITE_IMAGES_DIR_PATH + request . META [ 'REMOTE_ADDR' ] + '.jpg' tempname = request . META [ 'REMOTE_ADDR' ] + '.jpg' im . save ( temp , "JPEG" ) if request . POST : data = request . POST . copy () # does the captcha math ? if data [ 'imghash' ] == sha . new ( SALT + data [ 'imgtext' ]) . hexdigest (): # captcha ok # save data etc. # use another view/template in render_to_response and delete the temp captcha file: #remove(temp) return render_to_response ( 'form.html' , { 'ok' : True , 'hash' : imghash , 'tempname' : tempname }) else : # captcha bad # return the form return render_to_response ( 'form.html' , { 'error' : True , 'hash' : imghash , 'tempname' : tempname }) # no post data, show the form else : return render_to_response ( 'form.html' , { 'hash' : imghash , 'tempname' : tempname })