Integrating Django forms with Twitter Bootstrap

With this template, you will be able to use Twitter Bootstrap with your Django forms. In this example, we assume our form is in the form variable.

<form class="form-horizontal" action="" method="POST" {% if form.is_multipart %}enctype="multipart/form-data"{% endif %}>
    {% csrf_token %}
    {{ form.media }}
    {% if form.errors %}
        <div class="alert alert-error">
            <ul>
                {% for error in form.non_field_errors %}
                    <li>{{ error }}</li>
                {% endfor %}
            </ul>
        </div>
    {% endif %}
    {% for field in form.visible_fields %}
        <div class="control-group {{ field.html_name }} {% if field.errors %}error{% endif %}">
            <label class="control-label">{{ field.label }}{% if field.field.required %} *{% endif %}</label>
            <div class="controls">
                {{ field }}
                {% if field.errors %}<span class="help-inline">{{ field.errors.as_text }}</span>{% endif %}
            </div>
        </div>
    {% endfor %}
    {% for field in form.hidden_fields %}
        {{ field }}
    {% endfor %}

    {% block formsets %}
        {% for formset in inlines %}
            {% include "inline_formset.html" with formset=formset %}
        {% endfor %}        
    {% endblock formsets %}

    <div class="form-actions">
        <input class="btn btn-primary btn-large" type="submit" value="Submit"/>
        {% block extra_buttons %}
        {% endblock extra_buttons %}
    </div>
</form>

This is how it looks in action:
Twitter Bootstrap in Django forms

Since this example is fairly generic, you can put it in a template and include it wherever you need it.

One comment on “Integrating Django forms with Twitter Bootstrap

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax