Django 模板:选择的详细版本 [英] Django templates: verbose version of a choice
问题描述
我有一个模型:
from django.db import models
CHOICES = (
('s', 'Glorious spam'),
('e', 'Fabulous eggs'),
)
class MealOrder(models.Model):
meal = models.CharField(max_length=8, choices=CHOICES)
我有一个表格:
from django.forms import ModelForm
class MealOrderForm(ModelForm):
class Meta:
model = MealOrder
我想使用 formtools.preview.默认模板打印选择的简短版本('e' 而不是 'Fabulous Egg'),因为它使用
And I want to use formtools.preview. The default template prints the short version of the choice ('e' instead of 'Fabulous eggs'), becuase it uses
{% for field in form %}
<tr>
<th>{{ field.label }}:</th>
<td>{{ field.data }}</td>
</tr>
{% endfor %}.
我想要一个和上面提到的一样通用的模板,但要打印Fabulous Eggs".
[因为我怀疑真正的问题在哪里,我为我们所有人加粗了:)]
我知道如何以一种本身丑陋的方式获得一个选择的详细版本:
I know how to get the verbose version of a choice in a way that is itself ugly:
{{ form.meal.field.choices.1.1 }}
真正的痛苦是我需要得到选定的选项,我想到的唯一方法是遍历选项并检查 {% ifequals currentChoice.0 choiceField.data %}
,这是更丑.
The real pain is I need to get the selected choice, and the only way coming to my mind is iterating through choices and checking {% ifequals currentChoice.0 choiceField.data %}
, which is even uglier.
可以轻松完成吗?或者它需要一些模板标签编程?django 中不应该已经提供了吗?
Can it be done easily? Or it needs some template-tag programming? Shouldn't that be available in django already?
推荐答案
在 Django 模板中,您可以使用 "get_FOO_display()
"方法,它将返回字段的可读别名,其中FOO"是字段的名称.
In Django templates you can use the "get_FOO_display()
" method, that will return the readable alias for the field, where 'FOO' is the name of the field.
注意:如果标准的 FormPreview
模板没有使用它,那么您可以随时为该表单提供您自己的模板,其中将包含类似 {{ form.get_meal_display }}
的内容.
Note: in case the standard FormPreview
templates are not using it, then you can always provide your own templates for that form, which will contain something like {{ form.get_meal_display }}
.
这篇关于Django 模板:选择的详细版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!