我有一个模型:
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 Eggs”),因为它使用
{% for field in form %}
<tr>
<th>{{ field.label }}:</th>
<td>{{ field.data }}</td>
</tr>
{% endfor %}.
我想要一个像上面提到的那样通用的模板,但要打印“神话般的鸡蛋”。
[因为我怀疑真正的问题在哪里,所以我为我们所有人加粗了:)]
我知道如何以一种本身很难看的方式获得选择的详细版本:
{{ form.meal.field.choices.1.1 }}
真正的痛苦是我需要得到选定的选项,而我想到的唯一方法是遍历选项并检查 {% ifequals currentChoice.0 choiceField.data %}
,这更难看。
可以轻松完成吗?或者它需要一些模板标签编程?那不应该已经在 django 中可用了吗?
在 Django 模板中,您可以使用“get_FOO_display()
”方法,该方法将返回该字段的可读别名,其中“FOO”是该字段的名称。
注意:如果标准 FormPreview
模板没有使用它,那么您始终可以为该表单provide your own templates,其中将包含类似 {{ form.get_meal_display }}
的内容。
您的问题的最佳解决方案是使用辅助函数。如果选项存储在变量 CHOICES 中,并且存储所选选项的模型字段是“选择”,那么您可以直接使用
{{ x.get_choices_display }}
在您的模板中。这里,x 是模型实例。希望能帮助到你。
如果这个答案与上面列出的任何答案都是多余的,我深表歉意,但似乎还没有提供这个答案,而且看起来相当干净。这是我解决这个问题的方法:
from django.db import models
class Scoop(models.Model):
FLAVOR_CHOICES = [
('c', 'Chocolate'),
('v', 'Vanilla'),
]
flavor = models.CharField(choices=FLAVOR_CHOICES)
def flavor_verbose(self):
return dict(Scoop.FLAVOR_CHOCIES)[self.flavor]
我的视图将 Scoop 传递给模板(注意:不是 Scoop.values()),并且模板包含:
{{ scoop.flavor_verbose }}
根据 Noah 的回复,这是一个对没有选择的字段免疫的版本:
#annoyances/templatetags/data_verbose.py
from django import template
register = template.Library()
@register.filter
def data_verbose(boundField):
"""
Returns field's data or it's verbose version
for a field with choices defined.
Usage::
{% load data_verbose %}
{{form.some_field|data_verbose}}
"""
data = boundField.data
field = boundField.field
return hasattr(field, 'choices') and dict(field.choices).get(data,'') or data
我不确定是否可以为此目的使用过滤器。如果有人有更好的解决方案,我会很高兴看到它:) 谢谢诺亚!
我们可以通过 Noah 扩展过滤器解决方案,以便在处理数据和字段类型时更加通用:
<table>
{% for item in query %}
<tr>
{% for field in fields %}
<td>{{item|human_readable:field}}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
这是代码:
#app_name/templatetags/custom_tags.py
def human_readable(value, arg):
if hasattr(value, 'get_' + str(arg) + '_display'):
return getattr(value, 'get_%s_display' % arg)()
elif hasattr(value, str(arg)):
if callable(getattr(value, str(arg))):
return getattr(value, arg)()
else:
return getattr(value, arg)
else:
try:
return value[arg]
except KeyError:
return settings.TEMPLATE_STRING_IF_INVALID
register.filter('human_readable', human_readable)
我认为没有任何内置的方法可以做到这一点。但是,过滤器可能会起作用:
@register.filter(name='display')
def display_value(bf):
"""Returns the display value of a BoundField"""
return dict(bf.field.choices).get(bf.data, '')
然后你可以这样做:
{% for field in form %}
<tr>
<th>{{ field.label }}:</th>
<td>{{ field.data|display }}</td>
</tr>
{% endfor %}
您有 Model.get_FOO_display() 其中 FOO 是具有选择的字段的名称。
在您的模板中执行以下操作:
{{ scoop.get_flavor_display }}
在你的 models.py 中添加一个简单的函数:
def get_display(key, list):
d = dict(list)
if key in d:
return d[key]
return None
现在,您可以获得如下选择字段的详细值:
class MealOrder(models.Model):
meal = models.CharField(max_length=8, choices=CHOICES)
def meal_verbose(self):
return get_display(self.meal, CHOICES)
更新:我不确定,“pythonic”和“django-way”解决方案是否足够,但它有效。 :)
Noah 和 Ivan 的解决方案的扩展扩展版本。还修复了 Noah 的 Django 3.1 解决方案,因为 ModelChoiceIteratorValue
现在是不可散列的。
@register.filter
def display_value(value: Any, arg: str = None) -> str:
"""Returns the display value of a BoundField or other form fields"""
if not arg: # attempt to auto-parse
# Returning regular field's value
if not hasattr(value.field, 'choices'): return value.value()
# Display select value for BoundField / Multiselect field
# This is used to get_..._display() for a read-only form-field
# which is not rendered as Input, but instead as text
return list(value.field.choices)[value.value()][1]
# usage: {{ field|display_value:<arg> }}
if hasattr(value, 'get_' + str(arg) + '_display'):
return getattr(value, 'get_%s_display' % arg)()
elif hasattr(value, str(arg)):
if callable(getattr(value, str(arg))):
return getattr(value, arg)()
return getattr(value, arg)
return value.get(arg) or ''
不定期副业成功案例分享