jeffwillette / django-g-recaptcha

installable django app that processes the validation of google recaptcha
5 stars 1 forks source link

GOOGLE RECAPTCHA DJANGO DECORATOR

Build Status

Coverage Status

SETUP

1. Download and install

Everything up to version 0.2.2 is compatible with python 2.7, releases after 0.2.2 will only be compatible with python 3+

>>> pip install django-g-recaptcha

if you need python 2.7...

pip install django-g-recaptcha==0.2.2

2. Add site key and secret key (obtained from Google)...

Settings.py:


...

GOOGLE_RECAPTCHA_SITE_KEY = 'key_obtained_from_google'
GOOGLE_RECAPTCHA_SECRET_KEY = 'key_obtained_from_google'

3. Pass the site key to a view through context...

views.py:

from django.conf import settings
def view(request):

context = {
    'GOOGLE_RECAPTCHA_SITE_KEY': settings.GOOGLE_RECAPTCHA_SITE_KEY,
}

return render(request, 'template.html', context)

4. Add the google recaptcha script to the <head> of your HTML file

your_template.html:

<head>
    <script src='https://www.google.com/recaptcha/api.js'></script>
</head>

5. Add the recaptcha div with the site key passed in your context...

<div class="g-recaptcha" data-sitekey="{{ GOOGLE_RECAPTCHA_SITE_KEY }}"></div>

6. add the decorator to your views...

from g_recaptcha.validate_recaptcha import validate_captcha

@validate_captcha
def view(request):
    ...

7. Add g_recaptcha to your installed apps ...

INSTALLED_APPS += ('g_recaptcha')

On a successful captcha submission it will process the rest of the view, if it fails, it will render a template which says there was a problem with the captcha. Override or extend this template however you see fit. It also has some logic to detect whether the request is ajax, if it is ajax it will return a simple HttpResponse that can be input on the page instead of returning a full template

Testing

If you find that you need to get around the wrapper for unittesting, there is an attribute that contains the original view function that was passed to g_recaptcha. It can be called like this...

Whatever you wrapped viewname is, add ._original before the arguments

wrapped_view._original(request)