Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

python - Add class to Django label_tag() output

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 and I have tested it in the shell and I can do something like:

for field in form:
    print field.label_tag(attrs{'class':'Foo'})

I will see the class='Foo' in my output, but I don't see a way to add an attrs argument from the template - in fact, templates are designed specifically against that, no?

Is there a way in my form definition to define the class to be displayed in the label?

In the form, I can do the following to give the inputs a class

self.fields['some_field'].widget.attrs['class'] = 'Foo'

I just need to have it output the class for the <label /> as well.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Technique 1

I take issue with another answer's assertion that a filter would be "less elegant." As you can see, it's very elegant indeed.

@register.filter(is_safe=True)
def label_with_classes(value, arg):

    return value.label_tag(attrs={'class': arg})

Using this in a template is just as elegant:

{{ form.my_field|label_with_classes:"class1 class2"}}

Technique 2

Alternatively, one of the more interesting technique I've found is: Adding * to required fields.

You create a decorator for BoundField.label_tag that will call it with attrs set appropriately. Then you monkey patch BoundField so that calling BoundField.label_tag calls the decorated function.

from django.forms.forms import BoundField

def add_control_label(f):
    def control_label_tag(self, contents=None, attrs=None):
        if attrs is None: attrs = {}
        attrs['class'] = 'control-label'
        return f(self, contents, attrs) 
    return control_label_tag

BoundField.label_tag = add_control_label(BoundField.label_tag)    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...