Head over to heroku for a live demo. Tested with oTree v2.5.3.
There is also an example app that demonstrates how the captcha can be shown after a certain time has passed.
- sign up for reCAPTCHA
- select V2 with otherwise default options
- make sure to add
herokuapp.com
as the domain if you intend to use it with Heroku as your hosting provider. - for development, also add
localhost
- add
django-recaptcha
to the requirements_base.txt - install:
pip install -r requirements.txt
- add 'captcha' to otree extension apps:
# settings.py
EXTENSION_APPS = [
...,
'captcha',
]
- add recaptcha credentials the to your settings.py:
# settings.py
RECAPTCHA_PUBLIC_KEY = 'MyRecaptchaKey123'
RECAPTCHA_PRIVATE_KEY = 'MyRecaptchaPrivateKey456'
- alternatively, use environmental variables (on heroku):
# settings.py
RECAPTCHA_PUBLIC_KEY = environ.get('RECAPTCHA_PUBLIC_KEY', '')
RECAPTCHA_PRIVATE_KEY = environ.get('RECAPTCHA_PRIVATE_KEY', '')
- add a dummy field to the player, make sure it may be left blank:
# models.py
class Player(BasePlayer):
captcha = models.CharField(blank=True)
...
- import the recaptcha field in pages.py, then add it to the page:
# pages.py
from captcha.fields import ReCaptchaField
class Captcha(Page):
form_model = 'player'
form_fields = ['captcha']
def get_form(self, data=None, files=None, **kwargs):
frm = super().get_form(data, files, **kwargs)
frm.fields['captcha'] = ReCaptchaField(label='')
return frm
- add the captcha to your template:
# Captcha.html
{% block content %}
...
{% formfield player.captcha %}
{% endblock %}
This is heavily based on Philipp Chapkovski's answer on the oTree Google group. I made some adjustments to make it work with oTree 2.5.3.