Last active
June 19, 2021 03:53
-
-
Save sleepless-se/0da703f1df894584673d538cd09a5245 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
Backend setting in Django
- Make Recaptcha instance in the View class.
- Set publick on context in get_context_data().
- 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
Frontend setting in Django.
Add this code on the page template.
Insert this element in
Add this code in header or footer.