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?
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
    ....
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With