我想转换一个通过url传递给模板的int,但是它表示str函数没有定义.
我该如何解决这个问题?
这是我的代码:
{% extends "base.html" %}
{% block content %}
{% for post in posts %}
{% set year = post.date.year %}
{% set month = post.date.month %}
{% set day = post.date.day %}
{% set p = str(year) + '/' + str(month) + '/' + str(day) + '/' + post.slug %}
<h3>
<a href="{{ url_for('get_post', ID=p) }}">
{{ post.title }}
</a>
</h3>
<p>{{ post.content }}</p>
{% else: %}
There's nothing here, move along.
{% endfor %} …Run Code Online (Sandbox Code Playgroud) 我可以在 Django HTML 模板中获取这两个值:
但是当我进一步使用它们在 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 %} ,但也没有帮助。
请帮忙。我只需要针对登录用户的帖子的删除按钮。
Jinja2 模板代码:
{% if u.user_name == u.user_email %}
{{ u.user_email }}
{% else %}
{{ u.user_name }}<br />
{{ u.user_email }}
{% endif %}
Run Code Online (Sandbox Code Playgroud)
如果没有单独的名称,通常数据源会将 user_name 字段设置为 user_email。但是,有时根本没有为 user_name 字段定义任何内容。
问题在于,在上面的 Jinja2 代码中,如果 user_name 字段未定义/为空,则上面的测试评估为 false 并且两行都被吐出 - 其中之一是空白。
我不确定如何正确编写此测试语法。我已经阅读了文档并尝试了诸如Convert integer to string Jinja和比较 jinja2 模板中的两个变量之类的方法。我想我的数据类型有问题,我只是不确定如何编写此语法以使其正常工作。
任何帮助表示赞赏!