Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying bootstrap styles to django forms

I want to use bootstrap to get a decent website design, unfortunately I don't know how style the form fields. I am talking about this:

<form class="form-horizontal" method="POST" action="."> {% csrf_token %}
  {{ form.title.label }}
  {{ form.title }}
</form>

How is one supposed to design this?? I tried this:

<form class="form-horizontal" method="POST" action="."> {% csrf_token %}
  <div class="form-control">
    {{ form.title.label }}
    {{ form.title }}
  </div>
</form>

This obviously didn't gave me the wanted results.

How can I apply bootstrap styles to django forms?

like image 240
Foo Bar Avatar asked Oct 07 '15 07:10

Foo Bar


People also ask

How can I style Django forms?

Right now this form is using the default widgets, and it doesn't have any style, so, basically, it looks like this: So, to change it, we need to customize the appearance. You can customize widgets in two ways — it can be via widget instance or widget class. For this first example, I'll be using widget instance.

Can you use Bootstrap with Django?

It is very easy to use Bootstrap in Django. Since Bootstrap is a front-end framework, it completely consists of CSS & JavaScript files. These files are considered static on the server-side.

What is form Is_valid () in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.


1 Answers

If you prefer not to use 3rd party tools then essentially you need to add attributes to your classes, I prefer to do this by having a base class that my model forms inherit from

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

Can easily be adjusted... but as you see all my field widgets get the form-control css class applied

You can extend this for specific fields if you wish, here's an example of an inherited form having an attribute applied

class MyForm(BootstrapModelForm):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['name'].widget.attrs.update({'placeholder': 'Enter a name'})
like image 61
Sayse Avatar answered Sep 20 '22 22:09

Sayse