【问题标题】:How to add bootstrap class to Django CreateView form fields in the template?如何将引导类添加到模板中的 Django CreateView 表单字段?
【发布时间】:2016-01-31 20:10:26
【问题描述】:

我正在使用 Django CreateView,在模板中我可以单独设置标签和字段。但是,我无法添加我需要的引导类。目前,我有以下表格。

<form action="" method="post" class="form-horizontal">{% csrf_token %}
    <div class="form-group">
        <label class="control-label col-xs-1" for="name">{{ form.name.label }}:</label>
        <div class="col-xs-9">
            {{ form.name }}
        </div>

    </div>
    <div class="form-group">
        <label class="control-label col-xs-1" for="name">{{ form.code.label }}:</label>
        <div class="col-xs-9">
            {{ form.code }}
        </div>

    </div>
    <div class="form-group">
        <label class="control-label col-xs-1" for="name">{{ form.phone.label }}:</label>
        <div class="col-xs-9">
            {{ form.phone }}
        </div>

    </div>
    <input class="btn btn-primary col-xs-offset-1 col-xs-9" type="submit" value="Create" />
</form>

如何将类添加到模板变量名称、代码和电话?

【问题讨论】:

标签: django forms twitter-bootstrap class templates


【解决方案1】:

您只需要覆盖表单的__init__ 方法并使用相应的Bootstrap 类设置每个字段的widget.attrs。例如:

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['name'].widget.attrs = {
            'class': 'form-control'
        }
        self.fields['code'].widget.attrs = {
            'class': 'form-control'
        }
        self.fields['phone'].widget.attrs = {
            'class': 'form-control'
        }     

    class Meta:
        model = MyModel
        # your other Meta options

然后,在您的 CreateView 中,使用以下形式:

class YourView(CreateView):
    form_class = MyModelForm
    ....

【讨论】:

  • 会试试这个然后回来。谢谢。
猜你喜欢
  • 2021-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 2011-07-14
  • 2015-06-25
  • 1970-01-01
  • 2018-10-12
相关资源
最近更新 更多