nospamform

 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
views.py:
from nospamform import KeyForm, get_key
#Write something like this to your form:
class FormWithKey(forms.Form,KeyForm):
    ...
    key = forms.CharField(max_length=100, widget=forms.widgets.HiddenInput())

...
if request.method == 'POST':
    f = FormWithKey(request.POST.copy())
    if f.is_valid():
        #do something useful
else:
    f = FormWithKey(initial={'key': get_key()})
...


nospamform.py:
from django.newforms.util import ValidationError
from django.utils.translation import ugettext as _
from time import time
from django.conf import settings
from Crypto.Cipher import Blowfish
from base64 import b64encode, b64decode

def get_key():
    cobj = Blowfish.new(settings.SECRET_KEY)
    text = unicode(time())
    text += "".join(["_" for i in xrange(8-len(text)%8)])
    return b64encode(cobj.encrypt(text))

class KeyForm():
    def clean_key(self):
        def validation_error():
            self.data['key'] = get_key()
            raise ValidationError(_('Incorrect key.'))

        cobj = Blowfish.new(settings.SECRET_KEY)
        text = cobj.decrypt(b64decode(self.cleaned_data['key'])).rstrip('_')
        try:
            key = float(text)
        except:
            validation_error()
        now = time()
        if now - key < 10 or now - key > 60*60*24:
            validation_error()
        return

Comments

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.