Django 模板对象类型

标签 django django-templates

好的,这是我的情况。我有一组通用对象,我正在 django 模板中对其进行迭代。这些对象有许多子类,我想在模板中找出我正在处理的子类。这可能吗?可取?

代码可能看起来类似于(其中 if 语句包含一些虚构的语法):

<table>
   <tr>
      <th>name</th>
      <th>home</th>
   </tr>
   {% for beer in fridge %}
   <tr>
      <td>
         {{ beer.name }}
      </td>
      <td>
          {% if beer is instance of domestic %}US of A{% endif %}
          {% if beer is instance of import %}Somewhere else{% endif %} 
      </td>
   </tr>
   {% endfor %}
</table>

最佳答案

这是一个老问题,但 FWIW 您可以使用模板过滤器来做到这一点。

@register.filter
def classname(obj):
    return obj.__class__.__name__

然后在您的模板中,您可以执行以下操作:
{% with beer|classname as modelclass %}
{% if modelclass == "Domestic" %}US of A
{% elif modelclass == "Import" %}Somewhere else
{% endif %}
{% endwith %}

关于Django 模板对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5427809/

相关文章:

python - Django DetailView 动态模型

Jquery .load() 在 Django 模板中不起作用

python - 在 Django 模板中获取页面 url 并缩短链接

python - 在 Django 模型中使用 save() 会产生 TypeError

python - 在哪里实例化 Django/Python 应用程序的几个部分中使用的对象?

python - POST 保存后更新模型中的字段之一

python - 查看 "add product"- 不起作用

django - 将值呈现为文本而不是Django表单中的字段

django - 在 Django 中自定义单选按钮

使用 Jquery 的 Django ajax 'like' 按钮?