justin
justin

Reputation: 1699

Django template comparing string

I'm new with django. I'm stuck with the problem of comparing string in the template.

I have use ifnotequal tag to compare string. But it is not working.

I have try to output the variable:

{{ request.user.username }} 
{{ article.creator }}

Here I compare:

{% ifnotequal request.user.username article.creator %}
    {# output something #}
{% endifnotequal %}

But when I do the hardcode: It works.

{% ifnotequal "justin" "mckoy" %}
    {# output something #}
{% endifnotequal %}

what is the problem? The article.creator is coming from the database and the user.username is from the request.

Can anyone help me with this issue?

Upvotes: 65

Views: 119049

Answers (5)

Sanket Suryawanshi
Sanket Suryawanshi

Reputation: 99

Note that if you do not put spaces before and after ==, Django could not parse the expression.

{% if MyProd.Status == "Processing" %}
       <button class="btn btn-outline-warning">{{MyProd.Status}}</button>
{% else %}
       <button class="btn btn-outline-success">{{MyProd.Status}}</button>
{% endif %}

Upvotes: 1

hopieman
hopieman

Reputation: 389

{% ifequal material.unit 'U' %}
    <p>are equals!<p/>
{% endifequal %}

Upvotes: 6

Nauman Tariq
Nauman Tariq

Reputation: 1400

For string compare in template use

{% if name == "someone" %}
   ............
   ............
{% endif %}

and for not equal

{% if name != "someone" %}
   ............
   ............
{% endif %}

Upvotes: 82

sandeep sangwan
sandeep sangwan

Reputation: 701

Try this:

{% ifnotequal article.creator|stringformat:"s" request.user.username %}

Upvotes: 70

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

article.creator is a User and request.user.username is a string. Try comparing request.user instead.

Upvotes: 30

Related Questions