Add class to Django label_tag() output

前端 未结 8 1181
独厮守ぢ
独厮守ぢ 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条回答
  •  Happy的楠姐
    2020-12-01 03:23

    class CustomBoundField(BoundField):
        def label_tag(self, contents=None, attrs=None):
            if self.field.required:
                attrs = {'class': 'required'}
            return super(CustomBoundField, self).label_tag(contents, attrs)
    
    class ImportViewerForm(forms.Form):
        url = fields.URLField(widget=forms.TextInput(attrs={'class': 'vTextField'}))
        type = fields.ChoiceField(choices=[('o', 'Organisation'), ('p', 'Program')], widget=forms.RadioSelect,
                                  help_text='Url contain infornation about this type')
        source = fields.ChoiceField(choices=[('h', 'hodex'), ('s', 'studyfinder')], initial='h', widget=forms.RadioSelect)
    
        def __getitem__(self, name):
            "Returns a BoundField with the given name."
            try:
                field = self.fields[name]
            except KeyError:
                raise KeyError('Key %r not found in Form' % name)
            return CustomBoundField(self, field, name)
    
    class Media:
        css = {'all': [settings.STATIC_URL + 'admin/css/forms.css']}
    

    You need change method label_tag in BoundField class, and use it in form

提交回复
热议问题