Reputation: 147
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?
Upvotes: 6
Views: 5127
Reputation: 43300
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'})
Upvotes: 12