Search code examples
pythondjangodjango-templatesdjango-context

How can I retrieve a list from context in my django template


I have a detail view with one model Room, in get_context_data method I add to my context another queryset of objects from second model:Worker

class RoomView(DetailView):
    template_name = 'detail.html'
    model = Room
    context_object_name = "room"

    def get_object(self):
        object = super(RoomView, self).get_object()
        if not self.request.user.is_authenticated():
            raise Http404
        return object

    def get_context_data(self, **kwargs):
        context = super(RoomView, self).get_context_data(**kwargs)
        context['workers'] = Worker.objects.all()
        print context
        return context

Context looks like:

{'workers': [<Worker: Michael Shchur, Backend>, <Worker: Toto Kutunyo, Backend>], u'object': <Room: Backend, id=1>, 'room': <Room: Backend, id=1>, u'view': <map.views.RoomView object at 0x7f257811dc10>}

But I can`t access to this added list of objects with {{room.workers}} or

{% for worker in room.workers %}
    <tr>
        <td>{{worker.id}}</td>
        <td>{{worker.first_name}}</td>
        <td>{{worker.last_name}}</td>
        <td>{{worker.email}}</td>
    </tr>
{% endfor %}.

Please advice me haw can I do it.


Solution

  • Provided context has a key workers so you need to use this name instead of room.workers:

    {% for worker in workers %}
    <tr>
        <td>{{worker.id}}</td>
        <td>{{worker.first_name}}</td>
        <td>{{worker.last_name}}</td>
        <td>{{worker.email}}</td>
    </tr>
    {% endfor %}.