[英]Context attributes not available in Django template
我正在尝试在 Django 的模板中显示特定属性。 我相信我已经在上下文中传递了正确的查询集,但由于某种原因,我只能访问 id 属性,而不是我需要的 title 属性。
视图.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]))
模型.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')
监视列表.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 %}
在模板中有listing.title 的地方,我只是得到空白,但是ul 项目符号列表项显示了一个指向适当列表的链接。 但是,如果我更改为 listing.id,id 属性将显示出来。 我做错了什么来显示列表的标题?
您正在模板中获取WatchedListing
的对象。 因此,要在那里获得标题,您需要通过ForeignKey
字段将其引用为
<li>{{ listing.watched_listing.title }}</li>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.