0
我的Django项目使用Bootstrap v4。如何以编程方式访问{{form.my_field.id_for_label}}?
我遍历所有字段以添加HTML属性class="form-control"
。我还需要添加一个HTML属性aria-describedby="{}Help"
,其中{}
是小部件的id_for_label
。
在模板语言中,我可以用{{ form.my_field.id_for_label }}
轻松打印该值,但是通过编程我不知道该怎么做。我试过ModelForm().fields['…'].widget.id_for_label()
,但该方法需要一个参数。通过查看Django源代码,返回值实际上是参数。
任何想法?
class AbonnentForm(ModelForm):
class Meta:
model = Abonnent
fields = '__all__'
def __init__(self, *args, **kwargs):
super(AbonnentForm, self).__init__(*args, **kwargs)
# Add Bootstrap class to all <input> elements.
for key, value in self.fields.items():
value.widget.attrs.update({'class': 'form-control'})
if value.help_text:
id_for_label = "{}Help".format(value.widget.id_for_label())
value.widget.attrs.update({'aria-describedby': id_for_label})
self.fields['erste_ausgabe'].widget.attrs.update({'placeholder':'MM/JJJJ'})
self.fields['letzte_ausgabe'].widget.attrs.update({'placeholder':'MM/JJJJ'})