0

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)

4

1 回答 1

0

Django 非常刻意地限制模板功能,以确保您最终不会像使用 PHP 那样在模板中编写整个网站。

来自The Django Book 2.0: Templates: Philosophies and Limitations

...在 Django 模板中直接调用 Python 代码是不可能的。所有的“编程”基本上都局限于模板标签可以做的范围内。

可以 编写一个自定义模板标签或过滤器来做你想做的事……但是——因为这似乎是表单逻辑——你几乎肯定做其他事情会更好。

最简单的可能是定义表单定义的标签/小部件。IE:

from django import forms

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

也就是说,对于小部件,还有其他记录在案的方式。如果您使用django-floppy-forms,您可以轻松覆盖用于呈现它们的整个模板。

最后,我强烈推荐django-crispyforms。它为您节省了大量时间,因为您不再有在模板中手写表单的痛苦。

于 2013-03-24T13:27:52.447 回答