6

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?

2
  • 3
    django-bootstrap3 will really make your life easier. github.com/dyve/django-bootstrap3 Commented Oct 7, 2015 at 8:03
  • @Quaker I will check that out, thank you! Commented Oct 7, 2015 at 8:04

1 Answer 1

12

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'})
Sign up to request clarification or add additional context in comments.

4 Comments

Well this is really cool! I don't like using 3 party tools but sticking more to the framework! I love it, thank you
@FooBar - No worries, enjoy! :)
this class would go into my forms.py file? noob question, i know. i just started learning django so i'm not 100% sure...
@Jeannie yea you can put it anywhere that makes sense really. You can import it throughout your projects as required

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.