MiniGunnR
MiniGunnR

Reputation: 5800

How to add bootstrap class to Django CreateView form fields in the template?

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?

Upvotes: 4

Views: 3154

Answers (1)

C&#233;sar
C&#233;sar

Reputation: 10119

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
    ....

Upvotes: 7

Related Questions