how to add captcha in django forms

  1. Install the required package: bash pip install django-crispy-forms django-recaptcha

  2. Add 'crispy_forms' and 'captcha' to your INSTALLED_APPS in the settings.py file: python INSTALLED_APPS = [ # ... 'crispy_forms', 'captcha', ]

  3. Set the form renderer to 'django_crispy_forms.bootstrap4' in the settings.py file: python CRISPY_TEMPLATE_PACK = 'bootstrap4'

  4. Run migrations to create necessary database tables: bash python manage.py migrate

  5. Get reCAPTCHA keys from the Google reCAPTCHA website: https://www.google.com/recaptcha

  6. Add the keys to the settings.py file: python RECAPTCHA_PUBLIC_KEY = 'your_public_key' RECAPTCHA_PRIVATE_KEY = 'your_private_key'

  7. Add the captcha field to your form: ```python from captcha.fields import ReCaptchaField

class YourForm(forms.Form): # Your existing form fields here

   captcha = ReCaptchaField()

```

  1. In your form template, load the crispy forms and render the form with the captcha field: ```html {% extends 'base.html' %}

{% block content %}

{% csrf_token %} {{ form|crispy }}
{% endblock %} ```

  1. In your view, validate the captcha field: ```python from django.shortcuts import render, redirect from .forms import YourForm

def your_form_view(request): if request.method == 'POST': form = YourForm(request.POST) if form.is_valid(): # Your form processing logic here return redirect('success_page') else: form = YourForm()

   return render(request, 'your_template.html', {'form': form})

```

  1. Customize your template to display error messages for the captcha field, if needed: html {% if form.captcha.errors %} <div class="alert alert-danger"> {{ form.captcha.errors }} </div> {% endif %}