【问题标题】:The If equal not working in Django TemplateIf equal 在 Django 模板中不起作用
【发布时间】:2020-07-12 07:20:06
【问题描述】:

我能够在 Django HTML 模板中获取这两个值:

{{ user.get_username }}

{{ post.user }}

但是当我进一步使用它们在 IF 条件下比较它们的值时,它不起作用。

 {%for post in post%}
              <a href="{% url 'post_detail' post.id %}"><h1>{{post.title}}</h1></a>
              <h2>{{post.content}}</h2>
              <p>{{post.date}}</p>
                {%if user.is_authenticated%}
                  <h3> {{ user.get_username }}</h3>
                  <h3> {{post.user}} </h3>
                    {%ifequal user.get_username post.user%}
                      <form action="{%url 'post_delete' post.id %}" method="POST">
                        {%csrf_token%}
                        <button type="submit">Delete</button>
                      </form>
                    {%endifequal%}
                {%endif%}
            {%endfor%}

我也尝试过 {% if user.get_username == post.user %},但也没有用。

请帮忙。我只需要针对已登录用户的帖子删除按钮。

【问题讨论】:

  • 你能分享一下输出吗?
  • 显示所有帖子的帖子标题和帖子内容。而已。但没有删除按钮,即使用户已登录。
  • 是否可以使两个值相等但某些字符的大小写有所不同?有的是小写的,有的是大写的?
  • 当我在模板中这样渲染它们时它们完全一样:{{ user.get_username }} {{ post.user }}
  • 试试{% if user == post.user %}。 ifequal 已经过时了,你应该使用常规的 if 标记。

标签: python html django django-forms django-templates


【解决方案1】:

您是否尝试过此处提供的解决方案:

compare two variables in jinja2 template

{% if user.get_username|string() == post.user|string() %}

【讨论】:

  • 这不起作用并给出错误'invalid filter string()'
  • 这只有在 OP 使用 Jinja 模板时才有效。即使是,使用{% if user == post.user %} 会更简单
【解决方案2】:

{% if user == post.user %} 为我工作。 看起来“user.get_username”不起作用。只是“用户”工作。我想知道为什么。

【讨论】:

  • user.get_username() 返回一个字符串。 user 是一个 User 实例。它们不是相同的类型,因此它们不相等,即使{{ user }} 在模板中显示相同的字符串。
【解决方案3】:

{{ user.get_username }} 和 {{ post.user }} 是不同的对象。

如果您想比较两者的“字符串”表示(这就是您在渲染模板中看到的),您必须将 {{ post.user }} 转换为字符串。 (我会同时转换它们,因为我不知道你的 user_name 是否也是一个字符串(不过应该是)。 使用:

{% if user.get_username|stringformat:'s' == post.user|stringformat:'s' %}

在此处查看文档:

Django Template Tag: Stringformat

Python Conversion Types (I.e. 's')

【讨论】:

    【解决方案4】:

    {% if notification.status|stringformat:'s' == 'Approved' %} &lt;td&gt;&lt;div class="badge badge-success"&gt;{{ notification.status }}&lt;/div&gt;&lt;/td&gt; {% else %} &lt;td&gt;{{ notification.status }}&lt;/td&gt; `{% endif %}'

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2018-02-26
    • 2020-08-09
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    相关资源
    最近更新 更多