简体   繁体   中英

How to provide Django label_tag and as_widget arguments (e.g. contents and attrs)

From django/forms/forms.py:

def label_tag(self, contents=None, attrs=None):
    ..

def as_widget(self, widget=None, attrs=None, only_initial=False):
    ..

From my templates I call the label_tag as follows:

{{ form.my_field.label_tag }}

which outputs the label.

How should I provide the arguments to those tag as in their definition? For example I want to provide an alternative label text and css classes.

I tried something like:

{{ form.my_field.label_tag contents='My alternative label' }}

but it gives me:

Could not parse the remainder: ' contents='My alternative label'' from 'form.code.label_tag contents='My alternative label''

The same goes for the attrs field. Can I supply a value for that one from the template. I would like to provide the css class. For css class I'm using a filter at the moment but while going through the Django source code I noticed label_tag and as_widget has these additional arguments, and that's why I'm wondering now I can supply them from my templates.

(I'm using Django 1.4 on App Engine)

Django very deliberately limits template functionality to ensure you don't end up writing the whole website in the template as you might with PHP.

From the The Django Book 2.0: Templates: Philosophies and Limitations :

...it's impossible to call Python code directly within Django templates. All “programming” is fundamentally limited to the scope of what template tags can do.

You could write a custom template tag or filter that does what you want... but — as this seems to be form logic — you would almost certainly be better off doing something else.

Simplest might be to define the label/widget where the form is defined. ie:

from django import forms

class MyForm(forms.Form):
    my_field = forms.CharField(label='My label', widget=forms.Textarea)

That said, for the widget, there are other documented ways . If you use django-floppy-forms you can easily override the whole template used to render them.

Finally, I highly recommend django-crispyforms . It saves you a lot of time because you no longer have the pain of hand-writing forms in templates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM