Skip to content
Browse files

Merge pull request #1 from Fandekasp/master

Improve MathCaptchaForm
  • Loading branch information...
2 parents 472c6ef + ac654e0 commit 6d1b5f55d9587751705b2b4f9abd76fb12ed65e8 @justquick committed Mar 1, 2012
Showing with 19 additions and 14 deletions.
  1. +1 −0 .gitignore
  2. +18 −14 math_captcha/forms.py
View
1 .gitignore
@@ -0,0 +1 @@
+*.swp
View
32 math_captcha/forms.py
@@ -9,41 +9,46 @@ class NullWidget(forms.widgets.HiddenInput):
def render(self, *a, **kw):
return ''
+
def math_clean(form):
"""
Cleans a form, validating answer to math question in the process.
- The given ``form`` must be an instance of either ``MathCaptchaModelForm`` or ``MathCaptchaForm``.
- Answer keys are communicated in the ``math_captcha_question`` field which is evaluated to give the correct answer
+ The given ``form`` must be an instance of either ``MathCaptchaModelForm``
+ or ``MathCaptchaForm``.
+ Answer keys are communicated in the ``math_captcha_question`` field which
+ is evaluated to give the correct answer
after being validated against the ``SECRET_KEY``
"""
try:
value = form.cleaned_data['math_captcha_field']
- test_secret, question = decode(form.cleaned_data['math_captcha_question'])
+ test_secret, question = decode(
+ form.cleaned_data['math_captcha_question'])
assert len(test_secret) == 40 and question
except (TypeError, AssertionError):
# problem decoding, junky data
raise forms.ValidationError('Invalid token')
except KeyError:
return
-
+
if encode(question) != form.cleaned_data['math_captcha_question']:
# security problem, hack attempt
raise forms.ValidationError('Invalid token')
if eval(question) != value:
raise forms.ValidationError('Wrong answer, try again')
+
class MathCaptchaModelForm(forms.ModelForm):
"""
Subclass of ``django.forms.ModelForm`` which contains the math fields
Inherit this class in your forms to add math captcha support::
-
+
class MyForm(MathCaptchaModelForm):
field1 = forms.fields.CharField()
# ...
-
+
class Meta:
model = MyModel
-
+
"""
math_captcha_field = MathField(label=settings.QUESTION)
math_captcha_question = forms.fields.CharField(widget=NullWidget())
@@ -52,21 +57,20 @@ def clean(self):
super(MathCaptchaModelForm, self).clean()
math_clean(self)
return self.cleaned_data
-
+
+
class MathCaptchaForm(forms.Form):
"""
Subclass of ``django.forms.Form`` which contains the math fields.
Inherit this class in your forms to add math captcha support::
-
+
class MyForm(MathCaptchaForm):
field1 = forms.fields.CharField()
# ...
-
+
"""
- math_captcha_field = MathField(label=settings.QUESTION)
math_captcha_question = forms.fields.CharField(widget=NullWidget())
+ math_captcha_field = MathField(label=settings.QUESTION)
- def clean(self):
- super(MathCaptchaForm, self).clean()
+ def clean_math_captcha_field(self):
math_clean(self)
- return self.cleaned_data

0 comments on commit 6d1b5f5

Please sign in to comment.
Something went wrong with that request. Please try again.