Trying to pass a dict which has various fields from a main table with additional data from the media table. The context is not getting to the html page, cant see why, any help would be appreciated.
I have a very similar view using POST request which works without issue. Both test prints in the view return the correct values so must be an issue with the way the context is being passed to the html template.
views.py
def listing(request, listing_id):
if listing_id:
print(f"listing id: {listing_id}")
results = ListingDetail.objects.filter(listing_id=listing_id).prefetch_related('media_set').all()
print(results)
return render(request, 'members/listing_detail.html', {'listing': results})
else:
return render(request, 'general/search.html', {'listing': 'no data'})
html
<div class="card">
listing_id = {{ listing.listing_id }}
<div class="card-header">
<div id="carousel_main" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
{% for media_item in listing.media_set.all %}
<div class="carousel-item {% if forloop.counter == 1 %}active{% endif %}">
<img src="{{ media_item.media_url }}" class="d-block" alt="" width="100%">
</div>
{% endfor %}
</div>
urls.py
urlpatterns = [
path('listing/<int:listing_id>', views.listing, name='listing'),
]
2
Answers
It seems like there might be a small issue with the way you’re accessing the media_set in your template. The ListingDetail queryset is returned as a list, and when you try to access media_set in the template, it may not behave as expected. You should make sure to iterate over each item in the results list.
Try modifying your template as follows:
In this modification, I’m assuming that the ListingDetail queryset will always have at least one item since you’re using filter with a specific listing_id. If there’s a chance that the queryset could be empty, you might want to handle that case separately.
If this doesn’t resolve the issue, please provide more details on any error messages or unexpected behavior you’re encountering.
The problem is in the view: you pass a
QuerySet
, so a collection to the template, a collection has no.listing_id
.Use: