Django模板:详细版本的选择 [英] Django templates: verbose version of a choice

查看:201
本文介绍了Django模板:详细版本的选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型:

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'而不是神话蛋),因为它使用

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 %}.

我想要一个如上所述的一般模板,但打印神话蛋

[因为我怀疑真正的问题在哪里,我大胆地为我们所有人:)]

我知道如何以本身丑陋的方式获得选择的详细版本:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆