Django template comparing string

PythonDjangoDjango Templates

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

For string compare in template use

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

and for not equal

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

Solution 2 - Python

Try this:

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

Solution 3 - Python

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

Solution 4 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjustinView Question on Stackoverflow
Solution 1 - PythonNauman TariqView Answer on Stackoverflow
Solution 2 - Pythonsandeep sangwanView Answer on Stackoverflow
Solution 3 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 4 - PythonhopiemanView Answer on Stackoverflow