If equal 在 Django 模板中不起作用

Kar*_*mar 2 html python django django-templates django-forms

我可以在 Django HTML 模板中获取这两个值:

{{ user.get_username }}

{{ 帖子.用户 }}

但是当我进一步使用它们在 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%}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 8

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

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

{% if user.get_username|stringformat:'s' == post.user|stringformat:'s' %}
Run Code Online (Sandbox Code Playgroud)

在这里查看文档:

Django 模板标签:Stringformat

Python 转换类型(即 's')