Captcha without Freetype or the Python Imaging Library (PIL)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from django.forms.fields import CharField, MultiValueField
from django.forms.widgets import TextInput, MultiWidget, HiddenInput
from django import forms
from django.utils.safestring import mark_safe
import hashlib
import random


class CaptchaTextInput(MultiWidget):
	def __init__(self,attrs=None):
		widgets = (
			HiddenInput(attrs),
			TextInput(attrs),
		)
		super(CaptchaTextInput,self).__init__(widgets,attrs)

	def decompress(self,value):
		if value:
			return value.split(',')
		return [None,None]
		
	
	def render(self, name, value, attrs=None):
		ints = (random.randint(0,9),random.randint(0,9),)
		answer = hashlib.sha1(str(sum(ints))).hexdigest()
		#print ints, sum(ints), answer
		
		extra = "What is %d + %d?" % (ints[0], ints[1])
		value = [answer, u'',]
		
		return mark_safe(extra + super(CaptchaTextInput, self).render(name, value, attrs=attrs))


class CaptchaField(MultiValueField):
	widget=CaptchaTextInput
	
	def __init__(self, *args,**kwargs):
		fields = (
			CharField(show_hidden_initial=True), 
			CharField(),
		)
		super(CaptchaField,self).__init__(fields=fields, *args, **kwargs)
	
	def compress(self,data_list):
		if data_list:
			return ','.join(data_list)
		return None
		
		
	def clean(self, value):
		super(CaptchaField, self).clean(value)
		response, value[1] = value[1].strip().lower(), ''
		
		if not hashlib.sha1(str(response)).hexdigest() == value[0]:
			raise forms.ValidationError("Sorry, you got the security question wrong - to prove you're not a spammer, please try again.")
		return value

More like this

  1. Mathematical Captcha by dogada 5 years, 5 months ago
  2. ImageURLField for forms by insin 5 years, 8 months ago
  3. Crop and scale image to a given size by rpw 6 years ago
  4. ResizeImageField by wim 2 years, 7 months ago
  5. Alternative to Captchas (Without Human Interaction) by Archatas 4 years, 7 months ago

Comments

bl4th3rsk1t3 (on June 4, 2009):

there's a django-captcha app too.

http://code.google.com/p/django-captcha/

#

bl4th3rsk1t3 (on June 4, 2009):

whoops, meant to give you this link:

http://code.google.com/p/django-simple-captcha/

#

gregb (on June 7, 2009):

Yeah, I linked to that in the description of this snippet... the point of this script is to provide a captcha which doesn't rely on freetype - it uses a plain text question (ie "What is 3 + 4?") instead of an image.

#

(Forgotten your password?)