如何将引导程序类添加到模板中的Django CreateView表单字段? [英] How to add bootstrap class to Django CreateView form fields in the template?
本文介绍了如何将引导程序类添加到模板中的Django CreateView表单字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Django CreateView,并且在模板中我可以分别设置标签和字段。但是,我无法添加所需的引导程序类。目前,我有以下表单。
I am using Django CreateView and in the template I can individually set the label and fields. However, I cannot add the bootstrap classes that I need. Currently, I have the following form.
<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>
如何在类变量名称,代码和电话中添加类?
How can I add classes to the template variables name, code and phone?
推荐答案
您只需要覆盖表单的 __ init __
方法并设置每个字段的 widget.attrs
和相应的Bootstrap类。例如:
You just need to override the __init__
method of your form and set each field's widget.attrs
with the corresponding Bootstrap class. For example:
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 $中c $ c>,使用以下格式:
Then, in your CreateView
, use the form:
class YourView(CreateView):
form_class = MyModelForm
....
这篇关于如何将引导程序类添加到模板中的Django CreateView表单字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文