Django模板比较字符串

jus*_*tin 34 python django django-templates

我是django的新手.我坚持在模板中比较字符串的问题.

我使用ifnotequal标签来比较字符串.但它没有用.

我试着输出变量:

{{ request.user.username }} 
{{ article.creator }}
Run Code Online (Sandbox Code Playgroud)

在这里我比较:

{% ifnotequal request.user.username article.creator %}
    {# output something #}
{% endifnotequal %}
Run Code Online (Sandbox Code Playgroud)

但是当我做硬编码时:它有效.

{% ifnotequal "justin" "mckoy" %}
    {# output something #}
{% endifnotequal %}
Run Code Online (Sandbox Code Playgroud)

问题是什么?它article.creator来自数据库,user.username来自请求.

任何人都可以帮我解决这个问题吗?

小智 49

Try this:

{% ifnotequal article.creator|stringformat:"s" request.user.username %}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案需要更多的选票!把头撞在墙上! (6认同)

Nau*_*riq 42

用于模板使用中的字符串比较

{% if name == "someone" %}
   ............
   ............
{% endif %}
Run Code Online (Sandbox Code Playgroud)

并且不相等

{% if name != "someone" %}
   ............
   ............
{% endif %}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果在“==”前后没有添加空格,Django 将无法解析该表达式。 (3认同)
  • 使用它而不是 ifequal/ifnotequal,因为这些方法将在不久的将来被删除。参考 https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#ifequal-and-ifnotequal (2认同)

Ign*_*ams 19

article.creatorUserrequest.user.username是一个字符串.尝试比较request.user.

  • 当Django模板中两个不相等的东西时,它通常是变量的类型.它发生了好几次,我试图比较1和"1". (3认同)

hop*_*man 6

{% ifequal material.unit 'U' %}
    <p>are equals!<p/>
{% endifequal %}
Run Code Online (Sandbox Code Playgroud)