Home > Software engineering >  Django template comparing strings returning false?
Django template comparing strings returning false?

Time:11-12

I have in my template a button that should only be visible if

1 The user is signed in and; 2 The user is the one who posted the listing

but doesnt show up even if all the above conditions have been met, so i have this in my template:

{% if user.username == "{{ users }}" %}
    <form action="listing" method="GET">
        <input  type="submit" value="Close Listing" name="close">
    </form>
{% endif %}

where "{{users}}" is the username of whoever posted the listing, and thus if its a match, this user gets the button

views.py

listing = Listing.objects.all().filter(title=title).first()
user = listing.user

passing it to the template:

return render(request, "auctions/listing.html", {
     "users": user
})

Cant find what i am doing wrong

CodePudding user response:

Change your logic;

First:

listing = Listing.objects.all().filter(title=title).first()

# Change variable name, you should name your variables with their purpose
author = listing.user

return render(request, "auctions/listing.html", {
     "author": author
})

Second:

# No need to use {{ }} in condition because `Jinja` does it for you.
{% if request.user == author %} # {% if request.user.username == author.username %}
    <form action="listing" method="GET">
        <input  type="submit" value="Close Listing" name="close">
    </form>
{% endif %}

  • Related