8

So I have two models: Car and Picture. a car may have multiple pictures.

Now I want to use a list view to display all the cars along with one picture for each car, can someone tell me how can I do that? Below is my code

# models.py
class Car(models.Model):
  name = models.CharField(max_length=100)
class Picture(models.Model):
  car = models.ForeignKey(Car,related_name='pictures')
  picture = models.ImageField()

# views.py
class CarList(ListView):
  model = Car
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
JSNoob
  • 1,477
  • 2
  • 18
  • 31

3 Answers3

21

List view has a method get_context_data. You can override this to send extra context into the template.

def get_context_data(self,**kwargs):
    context = super(CarList,self).get_context_data(**kwargs)
    context['picture'] = Picture.objects.filter(your_condition)
    return context

Then, in your template you can access picture object as you wish.

I guess this should solve your problem.

Costantino Grana
  • 3,132
  • 1
  • 15
  • 35
Animesh Sharma
  • 3,258
  • 1
  • 17
  • 33
3

You can directly access the related Picture objects to each Car object by using car.pictures.all in your template.

So you could do something like,

{% for car in objects %}
    {{ car.name }}
    {% if car.pictures.all %}<img src="{{ car.pictures.all.0.picture.url }}" />{%endif %}
{% endfor %}

For more info, read up on Related Objects.

Rod Xavier
  • 3,983
  • 1
  • 29
  • 41
3

As I wanted to pass forms with queryset, following worked for me.

def get_queryset(self):
    return Men.objects.filter(your condition)

def get_context_data(self,**kwargs):
    context = super(Viewname,self).get_context_data(**kwargs)
    context['price_form']=PriceForm(self.request.GET or None)
    return context

Using get_queryset() you can define a base queryset that will be implemented by get_context_data() in super().