I'm just trying to run an if statement in html using django in the {% %} things. The statemnet is {% if listing in watchlist %}. Even though the listing is in watchlists, it doesn't make the if statement true.
I used {{ }} to see what watchlist and listing are. for {{ watchlist }} I got: <QuerySet [<Watchlists: 15: Dan1308 has added 3: The Bus (yes the cool airplane), starting at 3000 to watchlist>]>
for {{ listing }} I got: 3: The Bus (yes the cool airplane), starting at 3000
here's my views.py:
def listing(request, NewListings_id):
user = request.user
listing = NewListings.objects.get(pk=NewListings_id)
comments = Comments.objects.filter(listing=listing)
watchlist = Watchlists.objects.filter(user=user)
return render(request, "auctions/listing.html", {
"listing": listing,
"comments": comments,
"user": user,
"watchlist": watchlist
})
and here's my models.py:
class Watchlists(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
listing = models.ForeignKey(NewListings, on_delete=models.CASCADE)
def __str__(self):
return f"{self.id}: {self.user} has added {self.listing} to watchlist"
So, why is it not working?
watchlist = Watchlists.objects.filter(user=user)
listing = NewListings.objects.get(pk=NewListings_id)
listing
is a NewListings
instance, and watchlist
is a queryset of Watchlists
instances. So listing
isn't in the queryset.
Instead, there is a watchlist
instance in the queryset, where the listing
foreign key points to listing
.
A different approach would be to check whether the listing is in the watchlist in the view:
def listing(request, NewListings_id):
user = request.user
listing = NewListings.objects.get(pk=NewListings_id)
comments = Comments.objects.filter(listing=listing)
watchlist = Watchlists.objects.filter(user=user)
listing_in_watchlist = Watchlist.objects.filter(user=user, listing=listing).exists()
return render(request, "auctions/listing.html", {
"listing": listing,
"comments": comments,
"user": user,
"watchlist": watchlist,
"listing_in_watchlist": listing_in_watchlist,
})
Now, in the template, you can use {% if listing_in_watchlist %}
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.