Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import urllib
import json
class Recaptcha():
url = 'https://www.google.com/recaptcha/api/siteverify'
# Get secret an public key from https://www.google.com/recaptcha/admin/
secret = 'YOUR_SECRET_KEY'
site_key = 'YOUR_SITE_KEY'
def __init__(self, DEBUG=False):
if DEBUG:
self.secret = 'YOUR_LOCAL_SECRET_KEY'
self.site_key = 'YOUR_LOCAL_SITE_KEY'
def get_results(self, recaptcha_response: str) -> dict:
data = {
'secret': self.secret,
'response': recaptcha_response,
}
data = urllib.parse.urlencode(data).encode()
req = urllib.request.Request(self.url, data=data)
response = urllib.request.urlopen(req)
return json.loads(response.read().decode())
@sleepless-se

This comment has been minimized.

Copy link
Owner Author

@sleepless-se sleepless-se commented Jun 18, 2021

Frontend setting in Django.

Add this code on the page template.

Insert this element in

     <input type="hidden" name="recaptcha_response" id="recaptchaResponse">

Add this code in header or footer.

    <script src="https://www.google.com/recaptcha/api.js?render={{ public_key }}"></script>
    <script>
        $(document).ready(function () {
            grecaptcha.ready(function () {
                grecaptcha.execute(`{{ public_key }}`, {action: 'submit'}).then(function (token) {
                    document.getElementById('recaptchaResponse').value = token;
                });
            });
        });
    </script>
@sleepless-se

This comment has been minimized.

Copy link
Owner Author

@sleepless-se sleepless-se commented Jun 18, 2021

Backend setting in Django

  1. Make Recaptcha instance in the View class.
  2. Set publick on context in get_context_data().
  3. Get results by recaptca.get_results in form_valid().
class SignupView(CreateView):
    model = User
    form_class = UserForm
    template_name = "base/signup.html"
    success_url = reverse_lazy('base:signup_done')
    recaptcha = Recaptcha(DEBUG)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['site_key'] = self.recaptcha.site_key
        return context

    def form_valid(self, form):
        recaptcha_results = self.recaptcha.get_results(self.request)
        if recaptcha_results.get('success') != True:
            return HttpResponse('Google Captcha error',status=500)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment