4

I am using Django CreateView and in the template I can individually set the label and fields. However, I cannot add the bootstrap classes that I need. Currently, I have the following form.

<form action="" method="post" class="form-horizontal">{% csrf_token %}
    <div class="form-group">
        <label class="control-label col-xs-1" for="name">{{ form.name.label }}:</label>
        <div class="col-xs-9">
            {{ form.name }}
        </div>

    </div>
    <div class="form-group">
        <label class="control-label col-xs-1" for="name">{{ form.code.label }}:</label>
        <div class="col-xs-9">
            {{ form.code }}
        </div>

    </div>
    <div class="form-group">
        <label class="control-label col-xs-1" for="name">{{ form.phone.label }}:</label>
        <div class="col-xs-9">
            {{ form.phone }}
        </div>

    </div>
    <input class="btn btn-primary col-xs-offset-1 col-xs-9" type="submit" value="Create" />
</form>

How can I add classes to the template variables name, code and phone?

MiniGunnR
  • 5,590
  • 8
  • 42
  • 66
  • Possible duplicate of [Django Forms and Bootstrap - CSS classes and ](http://stackoverflow.com/questions/8474409/django-forms-and-bootstrap-css-classes-and-divs) – solarissmoke Nov 01 '15 at 03:41

1 Answers1

7

You just need to override the __init__ method of your form and set each field's widget.attrs with the corresponding Bootstrap class. For example:

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['name'].widget.attrs = {
            'class': 'form-control'
        }
        self.fields['code'].widget.attrs = {
            'class': 'form-control'
        }
        self.fields['phone'].widget.attrs = {
            'class': 'form-control'
        }     

    class Meta:
        model = MyModel
        # your other Meta options

Then, in your CreateView, use the form:

class YourView(CreateView):
    form_class = MyModelForm
    ....
César
  • 9,939
  • 6
  • 53
  • 74