Aug. 31, 2024

How To Implement Recaptcha In Your Django Application Form.

By Admin Timpat
  • 5k
  • 5k
  • 5k

To implement reCAPTCHA in the form section of your Django application, you'll need to follow these steps:

1. Get reCAPTCHA API Keys

Go to the Google reCAPCHA site and register your site. You'll get a Site Key and a Secret Key.

Note: Do not forget to add your local domain eg 127.0.0.1. This will enable you to test locally before committing your changes

2. Update settings.py

Add the reCAPTCHA settings to your settings.py file:

RECAPTCHA_PUBLIC_KEY = 'your-site-key'
RECAPTCHA_PRIVATE_KEY = 'your-secret-key'

3. Update Your Form

Add the reCAPTCHA field to your form. Here's an example of what to add to your form replacing your-site-key with your reCAPTCHA site key:

<div class=" col-lg-12">
    <div class="">
        <script src="https://www.google.com/recaptcha/api.js" async defer></script>
        <div class="g-recaptcha" data-sitekey="your-site-key"></div>
    </div>
</div>

Replace your-site-key with your actual reCAPTCHA site key.

4. Verify reCAPTCHA in the View

In your add_contact form  view, you'll need to verify the reCAPTCHA response before saving the contact information.

Update your view to include the following code:

def sub_comment(request):
  
    if request.method == 'POST':

        recaptcha_response = request.POST.get('g-recaptcha-response')
        data = {
            'secret': settings.RECAPTCHA_PRIVATE_KEY,
            'response': recaptcha_response
        }
        recaptcha_verify_url = 'https://www.google.com/recaptcha/api/siteverify'
        recaptcha_result = requests.post(recaptcha_verify_url, data=data).json()

        if not recaptcha_result.get('success'):
            return JsonResponse({'status': 'error', 'msg': "Invalid reCAPTCHA. Please try again.", 'redirect_url': ''}, content_type='application/json')

        add_contact = Contact()
        add_contact.name = request.post['full_name']
        add_contact.email = request.post['email']
        add_contact.message = request.POST["message"]
        add_contact.save()
        content_message = {'status': 'ok', 'message': _("Successful"), 'redirect_url': ''}
        return Response(content_message, status=status.HTTP_200_OK)
      else:
        return render(request, "contact.html", {} )

5. Test the Integration

Once everything is in place, test your form to ensure that the reCAPTCHA is properly validating before the form is submitted.

This setup will help ensure that only real users can submit comments on your site, reducing spam and bot submissions.

Prev Post
Next Post

Related Post

Leave a Comment

Comments

BACK TO TOP