0

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.

kapitoshka
  • 45
  • 1
  • 10

1 Answers1

2

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 %}.
Ivan Semochkin
  • 8,649
  • 3
  • 43
  • 75
  • voted with my thumb, can you help me with one more question. How can I filter those workers in that get_context_data so they correspond to the room detail view of what I open? Worker has a foreignkey field from Room in model. @Baterson – kapitoshka Jul 11 '16 at 10:27
  • @kapitoshka you not woted :) just put answer as resolved and thumb up, that's how SO works. About filter, always better ask new question, it will also more helpful for other guys. But You can just call `filter` of queryset like this `room = self.get_object()` , then `Worker.objects.filter(room=room)`, or put your name to filter, if `ForeighnKey` to `Room` named different – Ivan Semochkin Jul 11 '16 at 10:32
  • Now it seems ok. answer is resolved, can`t vote, not enought reputation. Thanks again it works again:) – kapitoshka Jul 11 '16 at 10:37