Add class to Django label_tag() output

前端 未结 8 1176
独厮守ぢ
独厮守ぢ 2020-12-01 02:53

I need some way to add a class attribute to the output of the label_tag() method for a forms field.

I see that there is the ability to pass in an attrs dictionary a

8条回答
  •  醉梦人生
    2020-12-01 03:25

    A bit too late but came across a similar problem. Hope this helps you.

    class MyForm(forms.ModelForm):
    
        def __init__(self, *args, **kwargs):
            super(MyForm, self).__init__(*args, **kwargs)
            self.fields['myfield1'].widget.attrs.update(
                {'class': 'form-control'})
            self.fields['myfield2'].widget.attrs.update(
                {'class': 'form-control'})
    
        def as_two_col_layout(self):
    
            return self._html_output(
                normal_row='
    %(label)s
    %(field)s%(help_text)s
    ', error_row='%s', row_ender='
    ', help_text_html=' %s', errors_on_separate_row=True) class Meta: model = mymodel fields = ['myfield1', 'myfield2']

提交回复
热议问题