【问题标题】:How to use __repr__ method within django template?如何在 Django 模板中使用 __repr__ 方法?
【发布时间】:2013-11-24 04:51:44
【问题描述】:

例如嵌套循环中有一个对象:

 {% for fieldset in inline_admin_form %}
                    {% for line in fieldset %}
                      {% for field in line %}

                        {% if field.is_hidden %} {{ field.field }} {% endif %}
                      {% endfor %}
                    {% endfor %}
                  {% endfor %}
              {% endif %}

现在我想查看field.field的类名和一些信息,所以我用field.field.__repr__()代替field.field

但是,django模板在更改后抱怨它:

Variables and attributes may not begin with underscores: 'field.field.__repr__'

有人知道吗?有没有更好的方法来调试 django 模板中的变量? (我尝试了{% debug %},但当我想检查嵌套循环中的变量时发现它很糟糕......)

【问题讨论】:

标签: python django django-templates


【解决方案1】:
{{ value|stringformat:'r' }}

使用字符串 % 运算符样式格式和使用 repr()r 格式

【讨论】:

    【解决方案2】:

    您可以轻松编写一个模板过滤器,让您可以执行{{ var|asrepr }}。请参阅文档,但它看起来像这样:

    @register.filter
    def asrepr(value):
        return repr(value)
    

    【讨论】:

      猜你喜欢
      • 2010-12-04
      • 2015-07-29
      • 1970-01-01
      • 2020-04-10
      • 2015-09-07
      • 2010-12-31
      • 1970-01-01
      • 2019-01-02
      • 2020-05-15
      相关资源
      最近更新 更多