The If equal not working in Django Template

Viewed 4166

I am able to fetch these two values in the Django HTML template :

{{ user.get_username }}

{{ post.user }}

But when I use them further to compare their values in an IF condition, it doesn't work.

 {%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%}

I've also tried {% if user.get_username == post.user %} as well, but it didn't help either.

Please help. I need the delete button only against the posts of logged in user.

4 Answers

{{ user.get_username }} and {{ post.user }} are different objects.

If you want to compare the "string" representation of both (thats what you see in the rendered template), you have to convert {{ post.user }} to a string. (I'd convert them both, since I don't know if you user_name is also a string (it should be, though). Use:

{% if user.get_username|stringformat:'s' == post.user|stringformat:'s' %}

Check documentation here:

Django Template Tag: Stringformat

Python Conversion Types (I.e. 's')

{% if user == post.user %} worked for me. Looks like 'user.get_username' was not working. Just 'user' worked. I wonder why though.

{% if notification.status|stringformat:'s' == 'Approved' %} <td><div class="badge badge-success">{{ notification.status }}</div></td> {% else %} <td>{{ notification.status }}</td> `{% endif %}'

Related