gpt4 book ai didi

python - If equal 在 Django 模板中不起作用

转载 作者:行者123 更新时间:2023-12-02 02:56:42 25 4
gpt4 key购买 nike

我能够在 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 }} 是不同的对象。

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

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

在此处查看文档:

Django Template Tag: Stringformat

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

关于python - If equal 在 Django 模板中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60955686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com