N
N
NerVik2016-04-01 14:19:28
Django
NerVik, 2016-04-01 14:19:28

How to display data from another model in django CVB ListView?

there are two models:

class ModelA(models.Model):
    model_b = models.ForeignKey('ModelB')
    ch_field0 = models.ImageField()


class ModelB(models.Model):
    ch_field1 = models.CharField()

and a simple CBV view:
class BooksList(ListView):
    model = ModelB

question: how to display an image from ModelA in this damn view?
in the DetailView it would be simple:
def get_context_data(self, **kwargs):
        context = super(__class__, self).get_context_data(**kwargs)
        context['mb'] = ModelB.objects.get(id=self.object.id).modela_set.all()
        return context

in fact, you need the same thing, only for ListView, but your head doesn’t cook anymore ;(

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2016-04-01
@NerVik

Are you passing the context to the template?
So the necessary context already flies into the template:

{% for obj in objects_list %}
   {% for img in obj.modela_set.all %}
      {{ img }}
   {% endfor %}
{% endfor %}

If this needs to be done in the view, get a list of objects in get_queryset(), and add any fields there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question