将引导程序样式应用于 Django 表单 [英] Applying bootstrap styles to django forms

查看:36
本文介绍了将引导程序样式应用于 Django 表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用引导程序来获得一个不错的网站设计,不幸的是我不知道表单字段的样式.我在说这个:

{% csrf_token %}{{ form.title.label }}{{ form.title }}</表单>

应该如何设计这个??我试过这个:

{% csrf_token %}<div class="form-control">{{ form.title.label }}{{ form.title }}

</表单>

这显然没有给我想要的结果.

如何将引导程序样式应用于 django 表单?

解决方案

如果你不喜欢使用 3rd 方工具,那么基本上你需要向你的类添加属性,我更喜欢通过拥有一个我的模型的基类来做到这一点表单继承自

class BootstrapModelForm(ModelForm):def __init__(self, *args, **kwargs):super(BootstrapModelForm, self).__init__(*args, **kwargs)对于迭代器中的字段(self.fields):self.fields[field].widget.attrs.update({类":表单控件"})

可以轻松调整...但是正如您所看到的,我的所有字段小部件都应用了表单控件 css 类

如果您愿意,您可以将其扩展到特定字段,这是应用了属性的继承表单的示例

class MyForm(BootstrapModelForm):def __init__(self, *args, **kwargs):super(MyForm, self).__init__(*args, **kwargs)self.fields['name'].widget.attrs.update({'placeholder': '输入名字'})

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?

解决方案

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

这篇关于将引导程序样式应用于 Django 表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆