首页 > 解决方案 > Django 3 在模板标签内连接的问题

问题描述

我想在 Django(版本 3)中的模板内连接一个字符串。我已经阅读了我能找到的关于这个主题的所有内容,并发现这应该是这样的:

{{ "ST" | add: item.id | stringformat:"08d" }}

但它会产生错误:

django.template.exceptions.TemplateSyntaxError: add requires 2 arguments, 1 provided

谁能照亮我的黑暗?

标签: pythondjangotemplatesdjango-template-filters

解决方案


正如@Willem Van Onsum 指出的那样,id(pk)是一个整数,必须在连接之前转换为字符串。此外,必须删除空间才能使其正常工作。请参阅:TemplateSyntaxError: 'with' 至少需要一个变量赋值

因此解决方案是:

    {% with n=item.id|stringformat:"08d" %}
        {{ "ST"|add:n }}
    {% endwith %}

还要感谢@jaswanth 的贡献。


推荐阅读