Author Picture

Kim Majali


Django reCAPTCHA Integration

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')
  
Read more

Django Fields Unique_Together

Author Avatar wrote on 08/06/2022


class CompanyCurreny(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    currency = models.ForeignKey(Currency, on_delete=models.CASCADE)

    class Meta:
        unique_together = ('company', 'currency',)

    def __str__(self):
        return str(self.currency)
Read more

Django Fields Related_Name

Author Avatar wrote on 08/06/2022

Related name is a must in case there 2 FKs in the model that point to the same table. For example in case of Bill of material
Read more

Upload_to File and Images

Author Avatar wrote on 08/06/2022

A folder

class MyModel(models.Model):
    # file will be uploaded to MEDIA_ROOT/uploads
    upload = models.FileField(upload_to='uploads/')
Read more

Data Types and Fields List

Author Avatar wrote on 08/06/2022

  • AutoField It An IntegerField that automatically increments.
  • BigAutoField It is a 64-bit integer, much like an AutoField except that it is guaranteed to fit numbers from 1 to 9223372036854775807.
  • BigIntegerField It is a 64-bit integer, much like an IntegerField except that it is guaranteed to fit numbers from -9223372036854775808 to 9223372036854775807.
Read more

Topics: IntegrationsModels

CRUDgen Django CRUD generator