3

I want to format my modelforms with bootstrap, and without any additional packages (just using the bootstrap source files). A particular form that I want configured:

class FoodForm(forms.ModelForm):

    class Meta:
        model = Food
        fields = ['name', 'company']
        exclude = ('user', 'edit')

The 'name' is a text field I'd want to be a bootstrap text field, and 'company' is a selection field (from a foreign key) that I'd want to be a bootstrap dropdown.

The current setup of the form template:

    {% extends "mainsite/base.html" %}

    {% block content %}

    <form method="POST" class="post-form">{% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn btn-primary">Save</button>
</form>
    </form> 

    {% endblock %}

What's best practice for formatting any django modelform field into bootstrap?

Marcus Dash
  • 55
  • 1
  • 5
  • possible duplicate of [How to add class, id, placeholder attributes to a field in django model forms](http://stackoverflow.com/questions/19489699/how-to-add-class-id-placeholder-attributes-to-a-field-in-django-model-forms) – rnevius Jul 25 '15 at 14:23
  • why not use crispy-forms? I know you mentioned you want to use vanilla bootstrap but this seems unnecessary since crispy forms are pretty light-weight. – miki725 Jul 25 '15 at 14:33

2 Answers2

17

The trick to bootstrap fields is injecting the form-control class into each field, and making sure each field lives inside a form-group dom element. To inject that class into each one of your fields, you could so something like:

class FoodForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(FoodForm, self).__init__(*args, **kwargs)
        for field in iter(self.fields):
            self.fields[field].widget.attrs.update({
                'class': 'form-control'
        })

Now, in your django template you can iterate through your forms fields, placing each one into a bootstrap'd form-group. For example:

<form method="POST" class="post-form">
    {% for field in form %}
    <div class="form-group">
        {{ field }}
    </div>
    {% endfor %}
</form>

I'll also say that this setup (Django + Bootstrap) is super common now adays, so googling "Bootstrap forms with django" should yield a wealth of knowledge on customizing this even further. Good luck!

Quentin Donnellan
  • 2,687
  • 1
  • 18
  • 24
1

Simply use Django Crispy Forms It is fairly easy and straight forward

KingNonso
  • 712
  • 7
  • 7