mise-en-production
[auf_framonde.git] / project / cmsplugin_contact_plus / simplemathcaptcha / fields.py
1 from __future__ import absolute_import
2 from __future__ import unicode_literals
3
4 from django import forms
5 from django.utils.translation import ugettext_lazy as _
6 from django.core.exceptions import ValidationError
7
8 from .widgets import MathCaptchaWidget
9 from .utils import hash_answer
10
11
12 class MathCaptchaField(forms.MultiValueField):
13 default_error_messages = {
14 'invalid': _('Please check your math and try again.'),
15 'invalid_number': _('Enter a whole number.'),
16 }
17
18 def __init__(self, *args, **kwargs):
19 self._ensure_widget(kwargs)
20 kwargs['required'] = True
21 # we skip MultiValueField handling of fields and setup ourselves
22 super(MathCaptchaField, self).__init__((), *args, **kwargs)
23 self._setup_fields()
24
25 def compress(self, data_list):
26 """Compress takes the place of clean with MultiValueFields"""
27 if data_list:
28 answer = data_list[0]
29 real_hashed_answer = data_list[1]
30 hashed_answer = hash_answer(answer)
31 if hashed_answer != real_hashed_answer:
32 raise ValidationError(self.error_messages['invalid'])
33 return None
34
35 def _ensure_widget(self, kwargs):
36 widget_params = self._extract_widget_params(kwargs)
37
38 if 'widget' not in kwargs or not kwargs['widget']:
39 kwargs['widget'] = MathCaptchaWidget(**widget_params)
40 elif widget_params:
41 msg = '%s must be omitted when widget is provided for %s.'
42 msg = msg % (' and '.join(list(widget_params)),
43 self.__class__.__name__)
44 raise TypeError(msg)
45
46 def _extract_widget_params(self, kwargs):
47 params = {}
48 for key in ('start_int', 'end_int'):
49 if key in kwargs:
50 params[key] = kwargs.pop(key)
51 return params
52
53 def _setup_fields(self):
54 error_messages = {'invalid': self.error_messages['invalid_number']}
55 # set fields
56 fields = (
57 forms.IntegerField(error_messages=error_messages,
58 localize=self.localize),
59 forms.CharField()
60 )
61 for field in fields:
62 field.required = False
63 self.fields = fields