{"id":20915736,"url":"https://github.com/kbytesys/django-recaptcha3","last_synced_at":"2025-04-13T09:36:47.950Z","repository":{"id":44707447,"uuid":"145478156","full_name":"kbytesys/django-recaptcha3","owner":"kbytesys","description":"Django reCaptcha v3 field/widget","archived":false,"fork":false,"pushed_at":"2022-01-29T19:59:51.000Z","size":55,"stargazers_count":67,"open_issues_count":9,"forks_count":37,"subscribers_count":10,"default_branch":"master","last_synced_at":"2024-03-29T05:25:34.666Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"lgpl-2.1","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kbytesys.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-08-20T22:49:45.000Z","updated_at":"2024-03-29T05:25:34.667Z","dependencies_parsed_at":"2022-09-10T13:21:00.440Z","dependency_job_id":null,"html_url":"https://github.com/kbytesys/django-recaptcha3","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kbytesys%2Fdjango-recaptcha3","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kbytesys%2Fdjango-recaptcha3/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kbytesys%2Fdjango-recaptcha3/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kbytesys%2Fdjango-recaptcha3/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kbytesys","download_url":"https://codeload.github.com/kbytesys/django-recaptcha3/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248691492,"owners_count":21146373,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-18T16:18:06.778Z","updated_at":"2025-04-13T09:36:47.917Z","avatar_url":"https://github.com/kbytesys.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Django reCaptcha v3 [![Build Status](https://travis-ci.org/kbytesys/django-recaptcha3.svg?branch=master)](https://travis-ci.org/kbytesys/django-recaptcha2)\n----\n\nThis integration app implements a recaptcha field for \u003ca href=\"https://developers.google.com/recaptcha/intro\"\u003eGoogle reCaptcha v3\u003c/a\u003e.\n\n**Warning:** this package is **not** compatible with django-recaptcha2\n\n----\n\n## How to install\n\nInstall the required package from pip (or take the source and install it by yourself):\n\n```bash\npip install django-recaptcha3\n```\n\nThen add django-recaptcha3 to your installed apps:\n\n```python\nINSTALLED_APPS = (\n    ...\n    'snowpenguin.django.recaptcha3',\n    ...\n)\n```\n\nAnd add your reCaptcha private and public key to your django settings.py and the default action name, recaptcha score threshold:\n\n```python\nRECAPTCHA_PRIVATE_KEY = 'your private key'\nRECAPTCHA_PUBLIC_KEY = 'your public key'\nRECAPTCHA_DEFAULT_ACTION = 'generic'\nRECAPTCHA_SCORE_THRESHOLD = 0.5\nRECAPTCHA_LANGUAGE = 'en' # for auto detection language, remove this from your settings\n# If you require reCaptcha to be loaded from somewhere other than https://google.com\n# (e.g. to bypass firewall restrictions), you can specify what proxy to use.\n# RECAPTCHA_FRONTEND_PROXY_HOST = 'https://recaptcha.net'\n\n```\n\nIf you have to create the apikey for the domains managed by your django project, you can visit this \u003ca href=\"https://www.google.com/recaptcha/admin\"\u003ewebsite\u003c/a\u003e.\n\n## Usage\n### Form and Widget\nYou can simply create a reCaptcha enabled form with the field provided by this app:\n\n```python\nfrom snowpenguin.django.recaptcha3.fields import ReCaptchaField\n\nclass ExampleForm(forms.Form):\n    [...]\n    captcha = ReCaptchaField()\n    [...]\n```\n\nForm validation of the ReCaptchaField causes us to verify the token returned from the client against the ReCaptcha servers and populates a dictionary containing the `score`, `action`, `hostname`, and `challenge_ts` fields as the form fields `cleaned_data`:\n\n```python\n    def formview(request):\n        if request.method == \"POST\":\n            form = ExampleForm(request.POST)\n            if form.is_valid():\n              captcha_score = form.cleaned_data['captcha'].get('score')\n```\n\nIf a communication problem occurs, the token supplied by the client is invalid or has expired then a ValidationError is raised.\n\n## Automatic Enforcement\n\nIf you want low scores to cause a ValidationError, pass an appropriate `score_threshold` to the `ReCaptchaField`, or set the configuration variable settings.RECAPTCHA_SCORE_THRESHOLD.\n\nThe default value for the threshold is 0.0, which allows all successful capture responses through for you to later check the value of `score`.\n\n```python\nfrom snowpenguin.django.recaptcha3.fields import ReCaptchaField\n\nclass ExampleForm(forms.Form):\n    [...]\n    captcha = ReCaptchaField(score_threshold=0.5)\n    [...]\n```\n\nYou can also set the private key on the \"private_key\" argument of the ReCaptchaField contructor if you want to override the one inside your configuration.\n\n### Templating\nYou can use some template tags to simplify the reCaptcha adoption:\n\n* recaptcha_init: add the script tag for reCaptcha api. You have to put this tag somewhere in your \"head\" element\n* recaptcha_ready: call the execute function when the api script is loaded\n* recaptcha_execute: start the reCaptcha check and set the token from the api in your django forms. Token is valid for 120s, after this time it is automatically regenerated.\n* recaptcha_key: if you want to use reCaptcha manually in your template, you will need the sitekey (a.k.a. public api key).\n  This tag returns a string with the configured public key.\n\nYou can use the form as usual.\n\n### Samples\n#### Simple\n\nJust create a form with the reCaptcha field and follow this template example:\n\n```django\n{% load recaptcha3 %}\n\u003chtml\u003e\n  \u003chead\u003e\n      {% recaptcha_init %}\n      {% recaptcha_ready action_name='homepage' %}\n  \u003c/head\u003e\n  \u003cbody\u003e\n    \u003cform action=\"?\" method=\"POST\"\u003e\n      {% csrf_token %}\n      {{ form }}\n      \u003cinput type=\"submit\" value=\"Submit\"\u003e\n    \u003c/form\u003e\n  \u003c/body\u003e\n\u003c/html\u003e\n```\n\n#### Custom callback\n\nThe callback can be used to allow to use the token received from the api in ajax calls or whatever\n\n```django\n{% load recaptcha3 %}\n\u003chtml\u003e\n  \u003chead\u003e\n      \u003cscript\u003e\n          function alertToken(token) {\n              alert(token);\n          }\n      \u003c/script\u003e\n      {% recaptcha_init %}\n      {% recaptcha_ready action_name='homepage' custom_callback='alertToken' %}\n  \u003c/head\u003e\n  \u003cbody\u003e\n    \u003cform action=\"?\" method=\"POST\"\u003e\n      {% csrf_token %}\n      {{ form }}\n      \u003cinput type=\"submit\" value=\"Submit\"\u003e\n    \u003c/form\u003e\n  \u003c/body\u003e\n\u003c/html\u003e\n```\n\n#### Multiple render example\n\nYou can render multiple reCaptcha without any extra effort:\n\n```django\n{% load recaptcha3 %}\n\u003chtml\u003e\n  \u003chead\u003e\n      {% recaptcha_init %}\n      {% recaptcha_ready action_name='homepage' %}\n  \u003c/head\u003e\n  \u003cbody\u003e\n    \u003cform action=\"?\" method=\"POST\"\u003e\n      {% csrf_token %}\n      {{ form1 }}\n      \u003cinput type=\"submit\" value=\"Submit\"\u003e\n    \u003c/form\u003e\n    \u003cform action=\"?\" method=\"POST\"\u003e\n      {% csrf_token %}\n      {{ form2 }}\n      \u003cinput type=\"submit\" value=\"Submit\"\u003e\n    \u003c/form\u003e\n  \u003c/body\u003e\n\u003c/html\u003e\n```\n\n#### Bare metal!\n\nYou can use the plain javascript, just remember to set the correct value for the hidden field in the form\n\n```django\n\u003chtml\u003e\n  \u003chead\u003e\n      \u003cscript src=\"https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key\"\u003e\u003c/script\u003e\n      \u003cscript\u003e\n        grecaptcha.ready(function() {\n          var grecaptcha_execute = function(){\n            grecaptcha.execute('reCAPTCHA_site_key', {action: 'homepage'}).then(function(token) {\n              document.querySelectorAll('input.django-recaptcha-hidden-field').forEach(function (value) {\n                  value.value = token;\n              });\n              return token;\n            })\n          };\n          grecaptcha_execute()\n          setInterval(grecaptcha_execute, 120000);\n        });\n      \u003c/script\u003e\n  \u003c/head\u003e\n  \u003cbody\u003e\n    \u003cform action=\"?\" method=\"POST\"\u003e\n      {% csrf_token %}\n      {{ form }}\n      \u003cinput type=\"submit\" value=\"Submit\"\u003e\n    \u003c/form\u003e\n  \u003c/body\u003e\n\u003c/html\u003e\n```\n\n\n## Testing\n### Test unit support\nYou can disable recaptcha field validation in unit tests by setting the RECAPTCHA_DISABLE env variable. This will skip the external call to Recaptca servers, returning a valid field with no data.\n\n```python\nos.environ['RECAPTCHA_DISABLE'] = 'True'\n```\nYou can use any word in place of \"True\", the clean function will check only if the variable exists.\n\nIf you set `RECAPTCHA_DISABLE` to be valid json, it will be interpreted as a mock captcha server response allowing you to mock score/hostname/action as required:\n```python\nos.environ['RECAPTCHA_DISABLE'] = json.dumps({'score': 0.4, 'hostname': 'localhost', 'action': 'homepage'})\n```\n\n### Test unit with recaptcha3 disabled\n```python\nimport os\nimport unittest\n\nfrom yourpackage.forms import MyForm\n\nclass TestCase(unittest.TestCase):\n    def setUp(self):\n        os.environ['RECAPTCHA_DISABLE'] = 'True'\n\n    def test_myform(self):\n        form = MyForm({\n            'field1': 'field1_value'\n        })\n        self.assertTrue(form.is_valid())\n\n    def tearDown(self):\n        del os.environ['RECAPTCHA_DISABLE']\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkbytesys%2Fdjango-recaptcha3","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkbytesys%2Fdjango-recaptcha3","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkbytesys%2Fdjango-recaptcha3/lists"}