Package: django-recaptcha
Django reCAPTCHADjango reCAPTCHA form field/widget integration app.[!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 thePython reCAPTCHA clientwhich is included in the package asclient.py.RequirementsInstallationUsageFieldsWidgetsreCAPTCHA V3 ScorereCAPTCHA V3 ActionLocal Development and Functional TestingCreditsRequirementsTested with:Python: 3.8, 3.9, 3.10, 3.11Django: 3.2, 4.1, 4.2You can view thePython-Django support matrix
hereThis package only supports modern, “evergreen” desktop and mobile
browsers. For IE11 support, make sure to add apolyfill for
Element.closest.InstallationSign up for reCAPTCHA.Install withpip install django-recaptcha.Add'django_recaptcha'to yourINSTALLED_APPSsetting.INSTALLED_APPS=[...,'django_recaptcha',...]Add the Google reCAPTCHA keys generated in step 1 to your Django
production settings withRECAPTCHA_PUBLIC_KEYandRECAPTCHA_PRIVATE_KEY. Note that omitting these settings will
default to a set of test keys refer toLocal Development and
Functional Testingfor
more information.For example:RECAPTCHA_PUBLIC_KEY='MyRecaptchaKey123'RECAPTCHA_PRIVATE_KEY='MyRecaptchaPrivateKey456'These can also be specified per field by passing thepublic_keyorprivate_keyparameters toReCaptchaField- see field usage
below.(OPTIONAL) If you require a proxy, add aRECAPTCHA_PROXYsetting
(dictionary of proxies), for example:RECAPTCHA_PROXY={'http':'http://127.0.0.1:8000','https':'https://127.0.0.1:8000'}(OPTIONAL) In the eventwww.google.comis not accessible theRECAPTCHA_DOMAINsetting can be changed towww.recaptcha.netas
per thereCAPTCHA
FAQ:RECAPTCHA_DOMAIN='www.recaptcha.net'This will change the Google JavaScript api domain as well as the client
side field verification domain.UsageFieldsThe quickest way to add reCAPTCHA to a form is to use the includedReCaptchaFieldfield class. AReCaptchaV2Checkboxwill be rendered
by default. For example:fromdjangoimportformsfromdjango_recaptcha.fieldsimportReCaptchaFieldclassFormWithCaptcha(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 theform
rendering
optionsandrendering fields
manuallysections of theofficial Django documentation for
forms.To allow for runtime specification of keys you can optionally pass theprivate_keyorpublic_keyparameters 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.WidgetsThere are three widgets that can be used with theReCaptchaFieldclass:ReCaptchaV2CheckboxforGoogle reCAPTCHA V2 - CheckboxReCaptchaV2InvisibleforGoogle reCAPTCHA V2 - InvisibleReCaptchaV3forGoogle reCAPTCHA V3To make use of widgets other than the default Google reCAPTCHA V2 -
Checkbox widget, simply replace theReCaptchaFieldwidget. For
example:fromdjangoimportformsfromdjango_recaptcha.fieldsimportReCaptchaFieldfromdjango_recaptcha.widgetsimportReCaptchaV2InvisibleclassFormWithCaptcha(forms.Form):captcha=ReCaptchaField(widget=ReCaptchaV2Invisible)The reCAPTCHA widget supports severaldata
attributesthat customize the behaviour of the widget, such asdata-theme,data-size, etc. You can forward these options to the widget by passing
anattrsparameter 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 severalparameters.
To customise the parameters that get sent along pass anapi_paramsparameter 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 atlanguage
codesfor 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_TWHowever, the JavaScript used by the widgets can easily be overridden in
the templates.The templates are located in:django_recaptcha/includes/js_v2_checkbox.htmlfor overriding the reCAPTCHA V2 - Checkbox templatedjango_recaptcha/includes/js_v2_invisible.htmlfor overriding the reCAPTCHA V2 - Invisible templatedjango_recaptcha/includes/js_v3.htmlfor overriding the reCAPTCHA V3 templateFor more information about overriding templates look atDjango's template overridereCAPTCHA V3 ScoreAs 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 Googledocumentationfor more details.To set a project wide score limit use theRECAPTCHA_REQUIRED_SCOREsetting.For example:RECAPTCHA_REQUIRED_SCORE=0.85For 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.reCAPTCHA V3 ActionGoogle's reCAPTCHA V3 API supports passing an action value.
Actions allow you to tie reCAPTCHA validations to a specific form on your site for analytical purposes, enabling you to perform risk analysis per form. This will allow you to make informed decisions about adjusting the score threshold for certain forms because abusive behavior can vary depending on the nature of the form.To set the action value, pass anactionargument when instantiating the ReCaptcha
widget. Be careful to only use alphanumeric characters, slashes and underscores as stated in the reCAPTCHA documentation.captcha=fields.ReCaptchaField(widget=widgets.ReCaptchaV3(action='signup'))Setting an action is entirely optional. If you don't specify an action, no action will be passed to the reCAPTCHA V3 API.Local Development and Functional TestingIfRECAPTCHA_PUBLIC_KEYandRECAPTCHA_PRIVATE_KEYare not set,
django-recaptcha will useGoogle's test
keysinstead. These
cannot be used in production since they always validate to true and a
warning will be shown on the reCAPTCHA. Google's test keys only work for
reCAPTCHA version 2.To bypass the security check that prevents the test keys from being used
unknowingly addSILENCED_SYSTEM_CHECKS = [..., 'django_recaptcha.recaptcha_test_key_error', ...]to your settings, here is an example:SILENCED_SYSTEM_CHECKS=['django_recaptcha.recaptcha_test_key_error']If you want to mock the call to Google's servers altogether, have a look
attest_fields.py:fromunittest.mockimportpatchfromdjango.testimportTestCasefromdjango_recaptcha.clientimportRecaptchaResponseclassTestFields(TestCase):@patch("django_recaptcha.fields.client.submit")deftest_client_success_response(self,mocked_submit):mocked_submit.return_value=RecaptchaResponse(is_valid=True)...CreditsOriginally developed byPraekelt ConsultingInspired Marco Fucci's blogpost titledIntegrating reCAPTCHA with Djangoclient.pytaken fromrecaptcha-clientlicensed MIT/X11 by Mike Crawford.reCAPTCHA copyright 2012 Google.AuthorsCurrent MaintainersAndrew Chen WangStorm HegPraekelt ConsultingShaun SephtonPeter PistoriusHedley RoosAltus BarryCilliers BlignautbTaylor DesignBrandon TaylorOtherBrooks TravisDenis MishchishinJoshua PeperRodrigo PrimosnnwolfAdriano Oriolicdvv7788Daniel Gatis CarrazzonipbfAlexey SubbotinSean StewartRob CharlwoodRuslan Kovtun