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.
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.
First, we need to install django-crispy-forms in our project. Open your terminal and run the following command:
pip install django-crispy-formsNext, we need to add 'crispy_forms' to our INSTALLED_APPS list in our project's settings file:
INSTALLED_APPS = [
# ...
'crispy_forms',
]Also, make sure to add the following to the bottom of your settings file:
CRISPY_TEMPLATE_PACK = 'bootstrap4' # Use the Bootstrap 4 template packNow, let's create a simple form using django-crispy-forms. In your app's forms.py, create a form:
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'))To render the form, in your template, include the following:
{% load crispy_forms_tags %}
<form method="post">
{% csrf_token %}
{{ form|crispy }}
</form>In your view, handle the form submission:
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})Which command is used to install `django-crispy-forms`?
What does `CRISPY_TEMPLATE_PACK` control in our settings file?