【问题标题】:Combining regroup with get_foo_display in Django templates在 Django 模板中将 regroup 与 get_foo_display 结合使用
【发布时间】:2010-04-30 00:38:39
【问题描述】:

我正在使用regroup 模板标签对Choices 字段上的查询集输出进行分组。在模型中:

  RESOURCE_TYPES = (
      ('tut','External tutorial'),
      ('read','Additional reading'),
      ('org','Company or organization'),                         
  )

restype = models.CharField('Resource type',max_length=6,choices=RESOURCE_TYPES)

在视图中:

resources = Resource.objects.filter(tutorial=tutorial)

在模板中:

{% regroup resources by restype as resource_list %}
{% for type in resource_list %}
<h3>{{type.grouper}}</h3>

所以 type.grouper 在页面上呈现为“tut”或“org”,而不是长格式。通常你会使用get_foo_display 语法来获取选择的值,而不是键。但是经过重组后,该值似乎不可用。我找不到在 {{type.grouper}} 上使用 get_foo_display 的方法。

仔细想想是有道理的,但解决方法是什么?谢谢。

【问题讨论】:

    标签: django templates


    【解决方案1】:

    如果你这样做会发生什么

    {% regroup resources by get_restype_display as resource_list %}
    

    【讨论】:

    • 有效!太棒了丹尼尔。我会为此提交一个文档补丁。
    • 简单、优雅,正是我想要的。一个赞成票似乎还不够。
    猜你喜欢
    • 2014-09-23
    • 2018-11-14
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多