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?
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.
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.
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.
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'})
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