1👍
✅
Thanks to Daniel Roseman’s comment, who suggested me to append results to a list I could resolve this issue.
Here is how I did it :
views.py
...
room_user = Room.objects.all()
my_rooms = []
for room in room_user:
rooms = room.messages.all()[:1]
my_rooms.append(rooms)
return render(request, "my_room.html", {
'rooms': my_rooms,
})
my_room.html
{% for room in rooms %}
{% for r in room %}
<p>{{ r.client }} {{ r.message }}</p>
<p>{{ r.timestamp }}</p>
{% endfor %}
{% endfor %}
0👍
Looking at the flow of your views.py code, it’s only going to pass the rooms object on the last iteration of the for loop into your template. I would suggest passing room_user
instead to the dictionary:
return render(request, "my_room.html", {
'room_user': room_user,
}
Then, in your template, you’ll want to build a nested for
loop:
{% for room in room_user %}
{% for rmessage in room.messages.all()[:1] %}
<p>{{ rmessage.client }} : {{ rmessage.message }}</p>
<p>{{ rmessage.timestamp }}</p>
{% endfor %}
{% endfor %}
- I couldn't store the values in database from the custom form in HTML page. Using Django
- Django Migration difference between dev and test postgres databases
- Double loop in Django template
- Django where should I put my CSS file
Source:stackexchange.com