Understanding Google reCAPTCHA in Django. I found this awesome answer to simply understand how to use API from Google reCAPTCHA.

import urllib, urllib2

def recaptcha(request, postdata):
    rc_challenge = postdata.get('recaptcha_challenge_field', '')
    rc_user_input = postdata.get('recaptcha_response_field', '').encode('utf-8')
    url = 'http://www.google.com/recaptcha/api/verify'
    values = {
        'privatekey': 'XXXXXXXXXXXXXXXXXXXXXXX',
        'remoteip': request.META['REMOTE_ADDR'],
        'challenge': rc_challenge,
        'response': rc_user_input
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)
    result = response.read().split()[0]
    return result

In your view check the following POST data:

def login_view(request, template_name="login.html"):   
    if request.method == 'POST':
        postdata = request.POST.copy()
        captcha = recaptcha(request, postdata)
        form = LoginUserForm(request, postdata)
        if captcha == "false":
            return render_to_response(template_name, locals(),
        if form.is_valid():
            # do authentication here
    # just display the login_form on GET request

You can use the variable “captcha” to render an error message in your template, if the user input returned false on the captcha. Youll also have to define your own LoginUserForm to use in a separate custom HTML template.

This is just a littel hacky concept from my head, I think, a more elegant way could be to write a custom captcha widget.

Hope these thoughts may lead to a possible solution.

146 7 7 0