Django What is the best way to format forms?

I have just gotten into Django and read a bunch of books, now im building my first app. When I render my forms in my template im using…

{{ form.as_ul }}

And now I’m trying to apply some CSS to my form. It’s proving difficult to get it look nice. I was wondering if there is a better way of rendering and styling forms?

Best answer

Well, there are a couple of options that you can take advantage of like:

  1. form.as_p
  2. form.as_ul
  3. form.as_table

Its up to you to decide what you would like. As for customizing it with CSS, take a look at how they structured the form here (taken from django docs):

<form action="/contact/" method="post">
    {{ form.non_field_errors }}
    <div class="fieldWrapper">
        {{ form.subject.errors }}
        <label for="id_subject">Email subject:</label>
        {{ form.subject }}
    </div>
    <div class="fieldWrapper">
        {{ form.message.errors }}
        <label for="id_message">Your message:</label>
        {{ form.message }}
    </div>
    <div class="fieldWrapper">
        {{ form.sender.errors }}
        <label for="id_sender">Your email address:</label>
        {{ form.sender }}
    </div>
    <div class="fieldWrapper">
        {{ form.cc_myself.errors }}
        <label for="id_cc_myself">CC yourself?</label>
        {{ form.cc_myself }}
    </div>
    <p><input type="submit" value="Send message" /></p>
</form>

The original form looked like this:

from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)

So, as you can see, you can just access the form element, by

{{ form.<element_name>.<element_properties> }}

You can add your own CSS to the labels or divs. Its totally up to you to decide what you want to do. On a side note, if you want forms formatted with Bootstrap 3, then might I suggest that you use django-crispyforms extension for django.