django-crispy-forms: A Comprehensive Guide 🎯

beginner
6 min

django-crispy-forms: A Comprehensive Guide 🎯

Introduction πŸ“

Welcome to our deep dive into django-crispy-forms! This powerful tool enhances Django's default form rendering, making it cleaner, more flexible, and easier to use. By the end of this tutorial, you'll be able to create stunning, user-friendly forms that will elevate your Django applications.

What is django-crispy-forms? πŸ’‘

django-crispy-forms is a third-party package that simplifies Django's form rendering. It allows you to structure your forms in a more readable and maintainable way, and it provides a set of predefined templates to make your forms look great.

Installing django-crispy-forms βœ…

First, we need to install django-crispy-forms in our project. Open your terminal and run the following command:

bash
pip install django-crispy-forms

Adding django-crispy-forms to our project βœ…

Next, we need to add 'crispy_forms' to our INSTALLED_APPS list in our project's settings file:

python
INSTALLED_APPS = [ # ... 'crispy_forms', ]

Also, make sure to add the following to the bottom of your settings file:

python
CRISPY_TEMPLATE_PACK = 'bootstrap4' # Use the Bootstrap 4 template pack

Creating a Form with django-crispy-forms βœ…

Now, let's create a simple form using django-crispy-forms. In your app's forms.py, create a form:

python
from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit class ContactForm(forms.Form): name = forms.CharField(label='Your Name') email = forms.EmailField(label='Your Email') message = forms.CharField(widget=forms.Textarea, label='Your Message') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Send Message'))

Rendering the Form βœ…

To render the form, in your template, include the following:

html
{% load crispy_forms_tags %} <form method="post"> {% csrf_token %} {{ form|crispy }} </form>

Handling Form Submission βœ…

In your view, handle the form submission:

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(): # Handle form data here pass else: form = ContactForm() return render(request, 'contact.html', {'form': form})
Quick Quiz
Question 1 of 1

Which command is used to install `django-crispy-forms`?

Quick Quiz
Question 1 of 1

What does `CRISPY_TEMPLATE_PACK` control in our settings file?