我正在尝试将CSS应用于html模板上的各个{{form}}字段。 我正在引用这个已解决的问题:
使用我创建的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'})
html使用{{form}}元素:
<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>
如何让“label”标签指向{{form.Fullname}}内的id。我的猜测是它现在没有这样做,因此它不适用于CSS。那个或我在forms.py中的小部件中指定的类不能正常工作。
答案 0 :(得分:1)
您可以使用field
的{{3}}属性:
使用此属性呈现此字段的ID。例如,如果您在模板中手动构建&lt; label&gt; 。
<div class="form-group">
<label for="{{ form.Fullname.id_for_label }}">Full Name:</label>
{{ form.Fullname }}
</div>
答案 1 :(得分:1)
<div class="form-group">
{% for field in form %}
<label for="id_Fullname" id="{{ field.name }}">Full Name:</label>
{{ field }}
{% endfor %}
</div>
试试这个
答案 2 :(得分:0)
这是将def init 函数放在Class Meta:而不是Class ContactInfo中的错误。我没有意识到我不正确地缩进了它。