相关疑难解决方法(0)

在Jinja2中投入到str

我想转换一个通过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)

python jinja2

29
推荐指数
2
解决办法
2万
查看次数

If equal 在 Django 模板中不起作用

我可以在 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 %} ,但也没有帮助。

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

html python django django-templates django-forms

2
推荐指数
1
解决办法
6477
查看次数

当一个值为空时jinja2字符串比较?

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 模板中的两个变量之类的方法。我想我的数据类型有问题,我只是不确定如何编写此语法以使其正常工作。

任何帮助表示赞赏!

jinja2

1
推荐指数
1
解决办法
1万
查看次数

标签 统计

jinja2 ×2

python ×2

django ×1

django-forms ×1

django-templates ×1

html ×1