extra context in django generic.listview
Asked Answered
F

3

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
Fluoro answered 13/4, 2015 at 5:22 Comment(0)
L
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.

Lasser answered 13/4, 2015 at 5:49 Comment(3)
Shouldn't it be car.picture_set.all ?Stickup
When you specify the related_name in a foreign key, you'll be able to use that in reverse relations.Lasser
Thank you so much! So that's how the related name worksFluoro
C
23

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.

Cariecaries answered 13/4, 2015 at 7:15 Comment(1)
Thanks :) I was missing "return context" at the end of my function.Decadent
L
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.

Lasser answered 13/4, 2015 at 5:49 Comment(3)
Shouldn't it be car.picture_set.all ?Stickup
When you specify the related_name in a foreign key, you'll be able to use that in reverse relations.Lasser
Thank you so much! So that's how the related name worksFluoro
M
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().

Medlock answered 1/8, 2019 at 4:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.