Django reCAPTCHA Integration Django.How

Author avatar wrote on 13/11/2023

1. Get a reCAPTCHA Account

  • Visit google.com/recaptcha Create Account
  • Choose V3
  • Add domains
  • Get keys and save them in settings.py

# reCAPTCHA
GOOGLE_RECAPTCHA_SITE_KEY = '6LfHCw0pAAasddasdasd'
GOOGLE_RECAPTCHA_SECRET_KEY = '6LfHCw0pasdasdasdasdas'
  

2. Create a reusable function to validate reCAPTCHA

install the request packages


pip install requests
  

We choose lib.py to create our reusable function


from django.conf import settings
import requests

def validate_recaptcha(request):
''' reCAPTCHA validation '''
recaptcha_response = request.POST.get('g-recaptcha-response')
data = {
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data)
result = r.json()

return result
  

Using reCAPTCHA

3. Edit the template

On any template, you want to use reCAPTCHA, add the reCAPTCHA field and script to the desired form

4. Edit the view

to the view


from .lib import validate_recaptcha

def my_view(request):
  if request.method == 'POST':
    # do your form validation
    if validate_recaptcha(request):
      #Save
    else:
      print('wrong recaptcha')
  
CRUDgen Django CRUD generator