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

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

问题描述

我想使用bootstrap来获得一个体面的网站设计,不幸的是我不知道style表单的样式。我在说这个:

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.

如何将自举样式应用于django表单?

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

可以轻松调整...但是,当您看到我的所有现场小部件获得form-control css类应用

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天全站免登陆