Applying bootstrap styles to django forms

99封情书 提交于 2019-12-27 11:25:09

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/32986780/applying-bootstrap-styles-to-django-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!