Add class to Django label_tag() output

前端 未结 8 1141
独厮守ぢ
独厮守ぢ 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:21
    @register.simple_tag
    def advanced_label_tag(field):
        """ Return form field label html marked to fill by `*` """
        classes = []
        attrs = {}
        contents = force_unicode(escape(field.label))
    
        if field.field.required:
            classes.append(u'required')
            contents = force_unicode('%s <span>*</span>'%escape(field.label))
    
        if classes:
            attrs['class'] = u' '.join(classes)
    
        return field.label_tag(contents=contents, attrs=attrs)
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 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='<div class="form-group"><span class="col-xs-2">%(label)s</span> <div class="col-xs-10">%(field)s%(help_text)s</div></div>',
                error_row='%s',
                row_ender='</div>',
                help_text_html=' <span class="helptext">%s</span>',
                errors_on_separate_row=True)
    
        class Meta:
    
            model = mymodel
            fields = ['myfield1', 'myfield2']
    
    0 讨论(0)
  • 2020-12-01 03:38

    I am agree with answer number one, with css this could be done, but. What is the reson for this to be in django source?

    In django.forms.forms.py there's this definition that shows there's code to display attrs in labels:

    class BoundField(StrAndUnicode): 
    # ....
    def label_tag(self, contents=None, attrs=None):
        contents = u'<label for="%s"%s>%s</label>' % (widget.id_for_label(id_), attrs, unicode(contents))
    

    but _html_output calls this function without attrs:

    label = bf.label_tag(label) or ''
    

    So it seems that django is partially prepared to this but actually it does not used it.

    0 讨论(0)
  • 2020-12-01 03:39

    How about adding the CSS class to the form field in the forms.py, like:

    class MyForm(forms.Form):
        title = forms.CharField(widget=forms.TextInput(attrs={'class': 'foo'}))
    

    then I just do the following in the template:

    <label for="id_{{form.title.name}}" class="bar">
        {{ form.title }}
    </label>
    

    Of course this can easily be modified to work within a for loop tag in the template.

    0 讨论(0)
  • 2020-12-01 03:39

    we can also use {{field.label}} and {{field.id_for_label}}

    <label class="your_class_name" id="{{form.link.id_for_label}}">{{form.link.label}}</label>

    Render in HTML as-

    <label class="your_class_name" id="id_name">Name</label>
    
    0 讨论(0)
提交回复
热议问题