Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extra context in django generic.listview

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
like image 548
JSNoob Avatar asked Apr 13 '15 05:04

JSNoob


People also ask

How do I add a context to a class-based view in Django?

There are two ways to do it – one involves get_context_data, the other is by modifying the extra_context variable. Let see how to use both the methods one by one. Explanation: Illustration of How to use get_context_data method and extra_context variable to pass context into your templates using an example.

Why do we need generic views in Django and where is the best use case?

The generic class-based-views was introduced to address the common use cases in a Web application, such as creating new objects, form handling, list views, pagination, archive views and so on. They come in the Django core, and you can implement them from the module django.

What does Get_queryset do in Django?

get_queryset(self)Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the queryset attribute.

What is Object_list in Django?

object_list will contain the list of objects (usually, but not necessarily a queryset) that the view is operating upon. Ancestors (MRO) This view inherits methods and attributes from the following views: django.


1 Answers

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.

like image 56
Animesh Sharma Avatar answered Sep 28 '22 08:09

Animesh Sharma