Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 239
MiniGunnR Avatar asked Mar 14 '23 07:03

MiniGunnR


1 Answers

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
    ....
like image 178
César Avatar answered Mar 16 '23 20:03

César