[Fixed]-How can I render values from a loop from views to template?

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 %}

Leave a comment