In this tutorial we are going to explore some of the Django Crispy Forms features to handle advanced/custom forms
rendering. This blog post started as a discussion in our community forum,
so I decided to compile the insights and solutions in a blog post to benefit a wider audience.
The Python code required to represent the form above is the following:
In this case I’m using a regular Form, but it could also be a ModelForm based on a Django model with similar
fields. The state field and the STATES choices could be either a foreign key or anything else. Here I’m just using
a simple static example with three Brazilian states.
Template:
Rendered HTML:
Rendered HTML with validation state:
Basic Crispy Form Rendering
Same form code as in the example before.
Template:
Rendered HTML:
Rendered HTML with validation state:
Custom Fields Placement with Crispy Forms
Same form code as in the first example.
Template:
Rendered HTML:
Rendered HTML with validation state:
Crispy Forms Layout Helpers
We could use the crispy forms layout helpers to achieve the same result as above. The implementation is done inside
the form __init__ method:
forms.py
The template implementation is very minimal:
The end result is the same.
Rendered HTML:
Rendered HTML with validation state:
Custom Crispy Field
You may also customize the field template and easily reuse throughout your application. Let’s say we want to use the
custom Bootstrap 4 checkbox:
From the official documentation, the necessary HTML to output the input above:
Using the crispy forms API, we can create a new template for this custom field in our “templates” folder:
custom_checkbox.html
Now we can create a new crispy field, either in our forms.py module or in a new Python module named fields.py
or something.
There is much more Django Crispy Forms can do. Hopefully this tutorial gave you some extra insights on how to use the
form helpers and layout classes. As always, the official documentation is the best source of information: