django-crispy-forms is a Django application, but Miguel thinks the talk will help you also with designing other systems and applications.
Django has three ways to render forms: as_ul
, as_p
, as_table
. They
do the same, but render themselves in a different way. Common questions by
people new to Django is “what about divs?” and “how to reorder fields?”. For
the last one, you need to switch the order of the form fields in your python
form code. There are some other tricks like overriding the
self.fields.keyOrder
attribute. If you have many fields, regular list
methods like delete() and pop() and insert() might help you.
But… ModelForms for the admin interface are different again: the abovementioned form tricks don’t work there. And those tricks sound a bit dirty anyway. So: how to customize the form output?
You can do a lot in by customizing the Django form in the template, but most
of it will be hardcoded and hand-tweaked that way. And if you customize a
form, you’ll often forget form.errors
and form.non_field_errors
, for
instance.
Django-crispy-forms was formerly known as django-uni-forms. It was created by pydanny in 2008, Miguel is now one of the main committers.
Crispy forms work on forms, modelforms and on formsets. A |crispy
filter
in the template renders your form as handy divs with better classes and IDs
which helps a lot if you want to customize your form with css. Neat!
Crispy also has a {% crispy %}
template tag. You can pass it a “form
helper”. A form helper is a global helper: it is decoupled from forms. So it
normally works with any form. There are some attributes on the form helper
that you can set, like method (get/post), form_id
, things like that.
You can customize such a helper specifically for one form and set the order of
the fields, for instance. There are so many things you might want to
customize; crispy supports/allows most/all of them with a Layout
class and
other layout classes like Div
. You can get really deep into the machinery
by letting crispy inject Django template code directly into the template…
For the ultimate in customizability, you can write your own layout class that renders itself in whatever way you want. Layouts can be nested, so there is a lot of flexibility here. You can also customize crispy’s own templates that it uses for fields and forms using the regular Django overwrite-a-template mechanism.
Handy: crispy forms has specific support for twitter bootstrap. This helps you get a nice looking form.
My name is Reinout van Rees and I program in Python, I live in the Netherlands, I cycle recumbent bikes and I have a model railway.
Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):