how to add captcha in django forms
Install the required package:
bash pip install django-crispy-forms django-recaptcha
Add 'crispy_forms' and 'captcha' to your
INSTALLED_APPS
in the settings.py file:python INSTALLED_APPS = [ # ... 'crispy_forms', 'captcha', ]
Set the form renderer to 'django_crispy_forms.bootstrap4' in the settings.py file:
python CRISPY_TEMPLATE_PACK = 'bootstrap4'
Run migrations to create necessary database tables:
bash python manage.py migrate
Get reCAPTCHA keys from the Google reCAPTCHA website: https://www.google.com/recaptcha
Add the keys to the settings.py file:
python RECAPTCHA_PUBLIC_KEY = 'your_public_key' RECAPTCHA_PRIVATE_KEY = 'your_private_key'
Add the captcha field to your form: ```python from captcha.fields import ReCaptchaField
class YourForm(forms.Form): # Your existing form fields here
captcha = ReCaptchaField()
```
- In your form template, load the crispy forms and render the form with the captcha field: ```html {% extends 'base.html' %}
{% block content %}
{% endblock %} ```- 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})
```
- 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 %}