-1

Actually, I am new in Django so I don't understand why if else statement doesn't work here. Is there anything super wrong with this code?

{%extends 'main/base.html'%}

{%block title%}
{{ title  }}
{%endblock%}


{%block content%}
<div class="container-fluid">
    <h2>{{user.first_name}}</h2>
    <p>{{user.second_name}}</p>
    <div class="col">
        {%for recel in receipts%}
            {%if recel.author is user.username%}
                <h2>Receipt: {{recel.title}}</h2>
                <h4>Doctor: {{recel.author}}</h4>
            {%else%}
                <span></span>
            {%endif%}
         {%endfor%}
    </div>
</div>

{%endblock%}

  • 1
    `is` checks if they are the same object. You want to check for equality, which is `==`. – Ted Klein Bergman Nov 28 '20 at 15:59
  • 1
    Does this answer your question? [Is there a difference between "==" and "is"?](https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is) It's not [DTL](https://docs.djangoproject.com/en/3.1/topics/templates/) (the framework Django is using to generate the HTML pages), but it's similar to python in many aspects. – Ted Klein Bergman Nov 28 '20 at 16:00

2 Answers2

0

is checks if the objects are the same object. You want to check for equality (if the objects have same value), which is done using ==.

{%if recel.author == user.username%}
    {%if recel.author is user.username%}
        <h2>Receipt: {{recel.title}}</h2>
        <h4>Doctor: {{recel.author}}</h4>
    {%else%}
        <span></span>
    {%endif%}
{%endfor%}

Django's Template Language (DTL) is similar to python in many aspects, and this answer explains in greater depth about the differences between is and ==.

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
0

if your using django's authentication.

replace:

{% if recel.author is request.user %}

with:

{%if recel.author is user.username%}
Reza GH
  • 1,504
  • 1
  • 8
  • 16