• Stars
    star
    929
  • Rank 48,832 (Top 1.0 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created over 14 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

New maintainers 🚧 --- Django reCAPTCHA form field/widget integration app.

Django reCAPTCHA

Django reCAPTCHA form field/widget integration app.

https://coveralls.io/repos/github/torchbox/django-recaptcha/badge.svg?branch=main

Note

django-recaptcha supports Google reCAPTCHA V2 - Checkbox (Default), Google reCAPTCHA V2 - Invisible and Google reCAPTCHA V3 please look at the widgets section for more information.

Django reCAPTCHA uses a modified version of the Python reCAPTCHA client which is included in the package as client.py.

Requirements

Tested with:

This package only supports modern, “evergreen” desktop and mobile browsers. For IE11 support, make sure to add a polyfill for Element.closest.

Installation

  1. Sign up for reCAPTCHA.

  2. Install with pip install django-recaptcha.

  3. Add 'captcha' to your INSTALLED_APPS setting.

    INSTALLED_APPS = [
        ...,
        'captcha',
        ...
    ]
  4. Add the Google reCAPTCHA keys generated in step 1 to your Django production settings with RECAPTCHA_PUBLIC_KEY and RECAPTCHA_PRIVATE_KEY. Note that omitting these settings will default to a set of test keys refer to Local Development and Functional Testing for more information.

    For example:

    RECAPTCHA_PUBLIC_KEY = 'MyRecaptchaKey123'
    RECAPTCHA_PRIVATE_KEY = 'MyRecaptchaPrivateKey456'

    These can also be specified per field by passing the public_key or private_key parameters to ReCaptchaField - see field usage below.

  5. (OPTIONAL) If you require a proxy, add a RECAPTCHA_PROXY setting (dictionary of proxies), for example:

    RECAPTCHA_PROXY = {'http': 'http://127.0.0.1:8000', 'https': 'https://127.0.0.1:8000'}
  6. (OPTIONAL) In the event www.google.com is not accessible the RECAPTCHA_DOMAIN setting can be changed to www.recaptcha.net as per the reCAPTCHA FAQ:

    RECAPTCHA_DOMAIN = 'www.recaptcha.net'

This will change the Google JavaScript api domain as well as the client side field verification domain.

Usage

Fields

The quickest way to add reCAPTCHA to a form is to use the included ReCaptchaField field class. A ReCaptchaV2Checkbox will be rendered by default. For example:

from django import forms
from captcha.fields import ReCaptchaField

class FormWithCaptcha(forms.Form):
    captcha = ReCaptchaField()

Be sure to include the captcha field in your forms. There are many ways to add fields to forms in Django. We recommend you refer to the form rendering options and rendering fields manually sections of the official Django documentation for forms.

To allow for runtime specification of keys you can optionally pass the private_key or public_key parameters to the constructor. For example:

captcha = ReCaptchaField(
    public_key='76wtgdfsjhsydt7r5FFGFhgsdfytd656sad75fgh',
    private_key='98dfg6df7g56df6gdfgdfg65JHJH656565GFGFGs',
)

If specified, these parameters will be used instead of your reCAPTCHA project settings.

Widgets

There are three widgets that can be used with the ReCaptchaField class:

ReCaptchaV2Checkbox for Google reCAPTCHA V2 - Checkbox

ReCaptchaV2Invisible for Google reCAPTCHA V2 - Invisible

ReCaptchaV3 for Google reCAPTCHA V3

To make use of widgets other than the default Google reCAPTCHA V2 - Checkbox widget, simply replace the ReCaptchaField widget. For example:

from django import forms
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV2Invisible

class FormWithCaptcha(forms.Form):
    captcha = ReCaptchaField(widget=ReCaptchaV2Invisible)

The reCAPTCHA widget supports several data attributes that customize the behaviour of the widget, such as data-theme, data-size, etc. You can forward these options to the widget by passing an attrs parameter to the widget, containing a dictionary of options. For example:

captcha = fields.ReCaptchaField(
    widget=widgets.ReCaptchaV2Checkbox(
        attrs={
            'data-theme': 'dark',
            'data-size': 'compact',
        }
    )
)
# The ReCaptchaV2Invisible widget
# ignores the "data-size" attribute in favor of 'data-size="invisible"'

The reCAPTCHA api supports several parameters. To customise the parameters that get sent along pass an api_params parameter to the widget, containing a dictionary of options. For example:

captcha = fields.ReCaptchaField(
    widget=widgets.ReCaptchaV2Checkbox(
        api_params={'hl': 'cl', 'onload': 'onLoadFunc'}
    )
)
# The dictionary is urlencoded and appended to the reCAPTCHA api url.

By default, the widgets provided only supports a single form with a single widget on each page.

The language can be set with the 'h1' parameter, look at language codes for the language code options. Note that translations need to be added to this package for the errors to be shown correctly. Currently the package has error translations for the following language codes: es, fr, nl, pl, pt_BR, ru, zh_CN, zh_TW

However, the JavaScript used by the widgets can easily be overridden in the templates.

The templates are located in:

captcha/includes/js_v2_checkbox.html for overriding the reCAPTCHA V2 - Checkbox template

captcha/includes/js_v2_invisible.html for overriding the reCAPTCHA V2 - Invisible template

captcha/includes/js_v3.html for overriding the reCAPTCHA V3 template

For more information about overriding templates look at Django's template override

reCAPTCHA v3 Score

As of version 3, reCAPTCHA also returns a score value. This can be used to determine the likelihood of the page interaction being a bot. See the Google documentation for more details.

To set a project wide score limit use the RECAPTCHA_REQUIRED_SCORE setting.

For example:

RECAPTCHA_REQUIRED_SCORE = 0.85

For per field, runtime, specification the attribute can also be passed to the widget:

captcha = fields.ReCaptchaField(
    widget=ReCaptchaV3(
        attrs={
            'required_score':0.85,
            ...
        }
    )
)

In the event the score does not meet the requirements, the field validation will fail as expected and an error message will be logged.

Local Development and Functional Testing

Google provides test keys which are set as the default for RECAPTCHA_PUBLIC_KEY and RECAPTCHA_PRIVATE_KEY. These cannot be used in production since they always validate to true and a warning will be shown on the reCAPTCHA.

To bypass the security check that prevents the test keys from being used unknowingly add SILENCED_SYSTEM_CHECKS = [..., 'captcha.recaptcha_test_key_error', ...] to your settings, here is an example:

SILENCED_SYSTEM_CHECKS = ['captcha.recaptcha_test_key_error']

You can use the env var RECAPTCHA_TESTING in unittests:

with mock.patch.dict(os.environ, {"RECAPTCHA_TESTING": "True"}):
    response = self.client.post(my_url,
        {
            "foo": "bar",
            ...
            "g-recaptcha-response": "PASSED",
        },
    )

Credits

Originally developed by Praekelt Consulting

Inspired Marco Fucci's blogpost titled Integrating reCAPTCHA with Django

client.py taken from recaptcha-client licenced MIT/X11 by Mike Crawford.

reCAPTCHA copyright 2012 Google.

More Repositories

1

django-pattern-library

UI pattern libraries for Django templates
Python
359
star
2

django-libsass

A django-compressor filter to compile SASS files using libsass
Python
265
star
3

vagrant-django-template

Skeleton project for a Django app running under Vagrant
Python
240
star
4

wagtailmedia

A Wagtail module for managing video and audio files within the admin
Python
231
star
5

wagtail-markdown

Markdown support for Wagtail
Python
191
star
6

wagtail-grapple

A Wagtail app that makes building GraphQL endpoints a breeze!
Python
152
star
7

wagtail-torchbox

Wagtail build of Torchbox.com
Python
124
star
8

wagtail-headless-preview

Previews for headless Wagtail setups
Python
116
star
9

wagtail-experiments

A/B testing for Wagtail
Python
105
star
10

vagrant-django-base

Vagrant configuration for a base box for Django development
Shell
90
star
11

storybook-django

Develop Django UI components in isolation, with Storybook
JavaScript
83
star
12

cookiecutter-wagtail

Python
54
star
13

k8s-hostpath-provisioner

Network storage provisioner for Kubernetes
Go
52
star
14

kdtool

Kubernetes deployment utility
Python
45
star
15

kube-ldap-authn

Kubernetes LDAP authentication service
Python
42
star
16

wagtail-wordpress-import

A package for Wagtail CMS to import WordPress blog content from an XML file into Wagtail
Python
41
star
17

wagtail-storages

Use AWS S3 with private documents in Wagtail
Python
40
star
18

design-in-browser-bootstrap

An aid to quickly starting Design In the Browser
JavaScript
34
star
19

wagtail-import-export

UNMAINTAINED. Try wagtail-transfer, the evolution of this package: https://github.com/wagtail/wagtail-transfer/
Python
32
star
20

wagtail-content-import

A module for importing page content into Wagtail from third-party sources. Docs:
Python
32
star
21

rustface-py

Python library for detecting faces in images.
Rust
31
star
22

wagtailquickcreate

Wagtail Quick Create offers shortcut links to create objects from models specified in your settings file.
Python
25
star
23

wagtailguide

An app for adding a CMS guide to your Wagtail CMS
Python
23
star
24

k8s-ts-ingress

Kubernetes Ingress controller as a Traffic Server plugin
C
22
star
25

wagtailsurveys

Python
21
star
26

vagrant-thumbor-base

Vagrant box providing a thumbor service over HTTP
Shell
20
star
27

wagtail-footnotes

Python
19
star
28

wagtail-template

A Django template for starting new Wagtail projects with Vagrant. NO LONGER MAINTANED
Python
19
star
29

wagtail-ab-testing

A/B testing for Wagtail
Python
17
star
30

buckup

Creating S3 buckets for your site with ease.
Python
16
star
31

torchbox-frontend

JavaScript
16
star
32

wagtail-appengine-demo

The simplest possible Wagtail site on Google Cloud
CSS
15
star
33

django-basic-auth-ip-whitelist

Hide your Django site behind basic authentication with IP whitelisting support
Python
14
star
34

verdant-rca

Python
13
star
35

docker-php

Docker PHP Images based on official PHP
Shell
12
star
36

longform

A plugin for longform content in Wagtail
CSS
12
star
37

wagtail-purge

A simple Wagtail admin UI for removing individual pages from your CDN's cache
Python
10
star
38

wagtail-webstories

AMP web story support for Wagtail
Python
9
star
39

cloudflare-recipes

Cloudflare service worker recipes
JavaScript
7
star
40

rca-wagtail-2019

Python
7
star
41

trafficserver-ingress-controller

Apache Traffic Server ingress controller for Kubernetes
Perl
7
star
42

tbxforms

A Torchbox-flavoured template pack for django-crispy-forms, adapted from crispy-forms-gds.
HTML
6
star
43

stylelint-config-torchbox

Shareable stylelint config for CSS and SCSS, following Torchbox’s code style.
JavaScript
6
star
44

wagtailapi

A module for adding a read only, JSON based web API to your Wagtail site (NO LONGER MAINTAINED! Use Wagtails contrib.wagtailapi module instead)
Python
6
star
45

webstories

Parser for AMP web stories
Python
6
star
46

wagtail-makeup

Wagtail plugin to replace all your broken local images with unsplash ones
Python
6
star
47

samaritans-patterns

HTML
5
star
48

wagtail-bookmarklet

Gives Wagtail editors an 'edit this page' bookmarklet, for scenarios where the user bar isn't available
Python
5
star
49

django-registration

Tweaked Django >=1.6-compatible version of django-registration
Python
5
star
50

careers

Torchbox careers site
TypeScript
4
star
51

ample

Cross-browser audio playback library, with HTML5 and Flash backends
JavaScript
4
star
52

nhs-organisations

Python
3
star
53

wagtail-jotform

A plugin for using jotforms in wagtail
Python
3
star
54

wagtail-bynder

Wagtail + Bynder Digital Asset Management System integration
Python
3
star
55

wagtailapidemo

Wagtaildemo with API enabled
Python
3
star
56

eslint-config-torchbox

Shareable ESLint config following Torchbox’s code style
JavaScript
3
star
57

wagtail-mongodb

Python
3
star
58

dit_directory_cms_poc

Proof-of-concepts for potential improvements to uktrade/directory-cms
Python
2
star
59

christmas-video-2017

CSS
2
star
60

wagtail-related

Python
2
star
61

resourcespace_plugin-api_markasused

API plugin for resourcespace that updates a resourcespace entry
PHP
2
star
62

wagtail-azure-cdn

Use Azure CDN with Wagtail CMS.
Python
2
star
63

heroku-cloudflare-app-domain

Create branded herokuapp.com domains through Cloudflare
Python
2
star
64

demo.wagtail.io

Configuration for demo.wagtail.io
Python
2
star
65

christmaschorus

the 2011 musical christmas card
JavaScript
2
star
66

ngxpurged

nginx cache purge daemon
Python
2
star
67

django-tagging

Fork via PyPI v0.3.4 to maintain Django compatibility. Unmaintained for Django >= 1.10
Python
2
star
68

torchbox.com

Torchbox website 2024 incarnation
Python
2
star
69

resourcespace_plugin-api_resource

API plugin for resourcespace that fetches a resource metadata or a resource file in stream
PHP
2
star
70

docker-rsync

Trivial Docker image containing Alpine Linux with rsync installed
Makefile
1
star
71

heroku-restarter

Restarts Heroku applications based on timeout alerts in Papertrail
Python
1
star
72

django-piston

Fork of the popular REST API mini-framework
Python
1
star
73

kube-registry-proxy

Shell
1
star
74

tate-cms

Tate CMS project’s sprint notes
1
star
75

docker-trafficserver

1
star
76

healtheintent-api-python

Python
1
star
77

raxtool

Rackspace Cloud management tool
Python
1
star
78

ceph-rbd-provisioner

1
star
79

django-importo

A developer-friendly framework for importing data into Django apps
Python
1
star
80

wagtail_picture_proposal

Code snippets for an experimental picture tag for Wagtail. Not intended for reuse
Python
1
star
81

nlbq

Natural language interface to BigQuery
Python
1
star
82

nuffield-nhs-timeline

Nuffield NHS Timeline
HTML
1
star