Context属性在Django模板中不可用



我想在Django的模板中显示一个特定的属性。我相信我已经在上下文中传递了正确的查询集,但由于某种原因,我只能访问id属性,而不是我需要的title属性。

Views.py:

@login_required
def watchlist_view(request):
listings = models.WatchedListing.objects.filter(owner = request.user)
return render(request, "auctions/watchlist.html", {"listings": listings})
@login_required
def add_to_watchlist(request, listing_id):
listing = models.Listing.objects.get(pk=listing_id)
user = request.user
currently_watched = models.WatchedListing.objects.filter(owner = request.user)
if listing in currently_watched.all():
messages.error(request, "This item is already on your watchlist.")
return redirect(reverse('listing', args=[listing.pk]))
else:
watchlist = WatchedListing()
watchlist.owner = user
watchlist.watched_listing = listing
watchlist.save()
messages.success(request, "Added to your watchlist!")
return redirect(reverse('listing', args=[listing.pk]))

Models.py:

class Listing(models.Model):
title = models.CharField(max_length=64)
description = models.TextField()
start_bid = models.ForeignKey(Bid, on_delete=models.CASCADE, related_name="start_bid")
image_url = models.TextField(null=True)
category = models.CharField(max_length=64, null=True)
current_bid = models.ForeignKey(Bid, on_delete=models.CASCADE, related_name="current_bid")
is_active = models.BooleanField()
owner = models.ForeignKey(User, on_delete=models.CASCADE)
num_bids = models.IntegerField()
created_at = models.DateTimeField(auto_now_add=True)
class WatchedListing(models.Model):
watched_listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name='watched_listings', blank=True, null=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name ='watchlist_owner')

watchlist.html:

{% extends "auctions/layout.html" %}
{% block title %} Watchlist {% endblock %}
{% block body %}
{% if messages %}
{% for message in messages %}
<strong style="color: red">{{ message }}</strong>
{% endfor %}
{% endif %}
{% if listings is not None %}
<ul>
{% for listing in listings %}
<a href = "{% url 'listing' listing_id=listing.id %}">
<li>{{ listing.title }}</li>
</a>
{% endfor %}
</ul>
{% else %}
No watched listings yet.
{% endif %}
{% endblock %}

我有列表。在模板的标题中,我只得到空格,但是ul项目列表项显示了一个到适当清单的链接。但是,如果我更改为列表。Id, Id属性会显示出来。我做错了什么让列表的标题显示?

您将在模板中获得WatchedListing的对象。这里要有title,需要通过ForeignKey字段引用

<li>{{ listing.watched_listing.title }}</li>

最新更新