1 from django import forms
2 from lib import captcha
3 from django.utils.safestring import mark_safe
4 from django.utils.encoding import force_unicode, smart_unicode
5 from django.utils.translation import ugettext_lazy as _
8 class ReCaptchaField(forms.Field):
9 def __init__(self, *args, **kwargs):
10 super(ReCaptchaField, self).__init__(widget=ReCaptchaWidget)
12 def clean(self, values):
13 super(ReCaptchaField, self).clean(values[1])
14 recaptcha_challenge_value = smart_unicode(values[0])
15 recaptcha_response_value = smart_unicode(values[1])
16 check_captcha = captcha.submit(recaptcha_challenge_value,
17 recaptcha_response_value, settings.RECAPTCHA_PRIV_KEY, {})
19 if not check_captcha.is_valid:
20 raise forms.util.ValidationError(_('Invalid captcha'))
25 class ReCaptchaWidget(forms.Widget):
26 def render(self, name, value, attrs=None):
27 return mark_safe(force_unicode(captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)))
29 def value_from_datadict(self, data, files, name):
31 return data.get('recaptcha_challenge_field', None), data.get('recaptcha_response_field', None)