简体   繁体   English

将引导样式应用于Django表单

[英]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? 如何将引导样式应用于Django表单?

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 可以轻松调整...但是如您所见,我所有的字段小部件都应用了表单控件css类

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM