Django Crispy Forms and Bootstrap 5 are powerful tools that can significantly enhance the user experience and streamline your development process when working with Django. By integrating these two libraries, you can create responsive, visually appealing forms with minimal effort. Let's explore how to use Django Crispy Forms with Bootstrap 5, using a practical example.

Before we dive into the example, ensure you have both Django Crispy Forms and Bootstrap 5 installed in your project. You can install them via pip:

```bash pip install django-crispy-forms npm install bootstrap@5 ```
Setting Up Django Crispy Forms with Bootstrap 5
Once installed, you need to configure Django Crispy Forms to use Bootstrap 5. In your project's settings.py file, add the following lines:

```python CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5" CRISPY_TEMPLATE_PACK = "bootstrap5" ```
Now, let's create a simple form to demonstrate the integration.
Creating a Basic Form

First, define a simple form in your app's forms.py file. For this example, let's create a ContactForm:
```python from django import forms class ContactForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() message = forms.CharField(widget=forms.Textarea) ```
Using the Form in a View
Next, include the form in a view. Here's how you can display the form and handle submissions:

```python from django.shortcuts import render from .forms import ContactForm def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # Process the data pass else: form = ContactForm() return render(request, 'contact.html', {'form': form}) ```
Creating the Template
Now, let's create the contact.html template to display the form. Using Django's template language and Bootstrap 5 classes, you can create a responsive form:
```html {% extends 'base.html' %} {% block content %}
Contact Us

Styling the Form
To make the form more visually appealing, you can add some custom CSS. In your base.html file, include the Bootstrap 5 CDN and add your custom styles:



















```html
With these steps, you've successfully integrated Django Crispy Forms with Bootstrap 5 to create a responsive, visually appealing contact form. This integration can significantly enhance the user experience of your Django project. Happy coding!