Skip to content

django recaptcha

Installation

  1. Sign up for reCAPTCHA.
  2. Install with pip install django-recaptcha.
  3. Add django_recaptcha to your INSTALLED_APPS setting.
INSTALLED_APPS = [
    ...,
    'django_recaptcha',
    ...
]

For example:

.env.example

RECAPTCHA_PUBLIC_KEY = 'MyRecaptchaKey123'
RECAPTCHA_PRIVATE_KEY = 'MyRecaptchaPrivateKey456'

settings.py

from dotenv import load_dotenv

#RECAPTCHA
RECAPTCHA_PUBLIC_KEY = os.environ.get('RECAPTCHA_PUBLIC_KEY')
RECAPTCHA_PRIVATE_KEY = os.environ.get('RECAPTCHA_PRIVATE_KEY')
RECAPTCHA_DOMAIN = 'www.recaptcha.net'

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 django_recaptcha.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:

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 django_recaptcha.fields import ReCaptchaField
from django_recaptcha.widgets import ReCaptchaV2Invisible

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

Reference