2

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.

Karan Kumar
  • 2,678
  • 5
  • 29
  • 65

4 Answers4

6

{{ 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')

Oilycoyote
  • 111
  • 1
  • 3
0

Did you tried solution provided here:

compare two variables in jinja2 template

{% if user.get_username|string() == post.user|string() %}
Renaud
  • 2,709
  • 2
  • 9
  • 24
0

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

Karan Kumar
  • 2,678
  • 5
  • 29
  • 65
  • `user.get_username()` returns a string. `user` is a `User` instance. They are not the same types, so they are not equal, even though `{{ user }}` displays the same string in the template. – Alasdair Mar 31 '20 at 17:49
0

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

Gowtham T
  • 1
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 24 '22 at 21:09