2017-03-21 141 views
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'}) 

回答

1

您可以自己contruct這樣說:

for key, value in self.fields.items(): 
    value.widget.attrs.update({'class': 'form-control'}) 

    if value.help_text: 
     django_id_for_label = self.auto_id % key # self.auto_id == 'id_%s' 
     my_id_for_label = '{}Help'.format(django_id_for_label) 
     value.widget.attrs.update({'aria-describedby': my_id_for_label})