我正在尝试将CSS应用于html模板上的各个{{form}}字段。我指的是这个已解决的问题:
Django 表单中的 CSS 样式
使用答案,我创建了我的 forms.py 页面,如下所示:
from django import forms
from .models import ContactInfo
class ContactForm(forms.ModelForm):
# class meta brings in the fields from models
class Meta:
model = ContactInfo
# grab the fields from models ContactInfo class
fields = ('Fullname')
# specify which bootstrap class each html widget should take
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['Fullname'].widget.attrs.update({'class': 'form-control'})
使用 {{form}} 元素的 html:
<div class="form-group">
<label for="id_Fullname">Full Name:</label>
{{form.Fullname}}
</div>
没有 {{form}} 用法的工作 html:
<div class="form-group">
<label for="fullname">Full Name:</label>
<input type="text" class="form-control" id="fullname">
</div>
如何让"标签"标签指向 {{form.全名}}。我的猜测是它现在没有这样做,因此它不应用 css。那个或我在 forms.py 的小部件中指定的类没有按照我想要的方式工作。
<div class="form-group">
{% for field in form %}
<label for="id_Fullname" id="{{ field.name }}">Full Name:</label>
{{ field }}
{% endfor %}
</div>
试试这个
field
的 id_for_label
属性:
使用此属性呈现此字段的 ID。例如,如果要在模板中手动构造<标签>标签>。
<div class="form-group">
<label for="{{ form.Fullname.id_for_label }}">Full Name:</label>
{{ form.Fullname }}
</div>
将def init函数放在Class Meta:而不是Class ContactInfo中的错误。我没有意识到我缩进得不恰当。