Login

reCAPTCHA integration

Author:
marco.fucci
Posted:
July 26, 2009
Language:
Python
Version:
1.0
Score:
11 (after 11 ratings)

Integrating reCAPTCHA with Django.

Warning: although remoteip is used as optional parameter in this snippet, it is likely to become mandatory in the future. Please see the comment by Jim Garrison for more detail.

Generic version of this snippet.

  1. Register on reCAPTCHA to get your public/private key pair
  2. Add your keys in settings.py
  3. Add recaptcha-client to your project
  4. Put ReCaptchaField and ReCaptcha widget somewhere (I've used a generic app marcofucci_utils)
  5. Configure your form

More information on my website marcofucci.com.

 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
57
58
59
60
61
62
#settings.py

    RECAPTCHA_PUBLIC_KEY = '<your public key>'
    RECAPTCHA_PRIVATE_KEY = '<your private key>'


#widgets.py

    from django import forms
    from django.utils.safestring import mark_safe
    from django.conf import settings
    from recaptcha import captcha
    
    class ReCaptcha(forms.widgets.Widget):
        recaptcha_challenge_name = 'recaptcha_challenge_field'
        recaptcha_response_name = 'recaptcha_response_field'
    
        def render(self, name, value, attrs=None):
            return mark_safe(u'%s' % captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY))
    
        def value_from_datadict(self, data, files, name):
            return [data.get(self.recaptcha_challenge_name, None), 
                data.get(self.recaptcha_response_name, None)]


#fields.py

    from django.conf import settings
    from django import forms
    from django.utils.encoding import smart_unicode
    from django.utils.translation import ugettext_lazy as _
    
    from marcofucci_utils.widgets import ReCaptcha
    from recaptcha import captcha
    
    class ReCaptchaField(forms.CharField):
        default_error_messages = {
            'captcha_invalid': _(u'Invalid captcha')
        }
    
        def __init__(self, *args, **kwargs):
            self.widget = ReCaptcha
            self.required = True
            super(ReCaptchaField, self).__init__(*args, **kwargs)
    
        def clean(self, values):
            super(ReCaptchaField, self).clean(values[1])
            recaptcha_challenge_value = smart_unicode(values[0])
            recaptcha_response_value = smart_unicode(values[1])
            check_captcha = captcha.submit(recaptcha_challenge_value, 
                recaptcha_response_value, settings.RECAPTCHA_PRIVATE_KEY, {})
            if not check_captcha.is_valid:
                raise forms.util.ValidationError(self.error_messages['captcha_invalid'])
            return values[0]


#forms.py

    class RegistrationForm(forms.Form):
        ...
        recaptcha = marcofucci_fields.ReCaptchaField()
        ...

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

s.federici (on January 22, 2010):

Hi, I had to change the import statement. from recaptcha.client import captcha

#

dreadicon (on June 23, 2013):

Excelent implementation! I have been using extremely hackish reCAPTCHA implementations till I found this. went from 5 files and 100+ lines of code to 2 files and about 50 lines. You have my eternal gratitude, sir.

#

Please login first before commenting.