Skip to content Skip to sidebar Skip to footer

Passing Django Queryset In Views To Template

I have a Django Views which has some logic for passing the correct category to the template. class ProductListView(ListView): model = models.Product template_name = 'catalo

Solution 1:

You can add the following method

defget_context_data(self, **kwargs):
    context = super(ProductListView, self).get_context_data(**kwargs)
    some_data = Product.objects.all()
    context.update({'some_data': some_data})
    return context

So now, in your template, you have access to some_data variable. You can also add as many data updating the context dictionary as you want.

If you still want to use the get_queryset method, then you can access that queryset in the template as object_list

{% for product in object_list %}
...
{% endfor %}

Solution 2:

Items from queryset in ListView are available as object_list in the template, so you need to do something like:

{% for product in object_list %}
            <tr><td><h5>{{ product.name }}</h5><p>Cooked with chicken and mutton cumin spices</p></td><td><p><strong>£ {{ product.price }}</strong></p></td><tdclass="options"><ahref="#0"><iclass="icon_plus_alt2"></i></a></td></tr>
            {% endfor %}

You can find details in the ListView documentation. Note a method called get_context_data - it returns a dictionary of variables and values, that will be passed to templates. You can always find why it works in this way in the source code.

Solution 3:

A more elegant way to pass data to the template context is to use the built-in view variable. So rather than overriding the get_context_data() method, you can simply create a custom method that returns a queryset:

defstores(self):
    return Store.objects.all()

Then you can use this in the template:

{% for store in view.stores %}
  ...
{% endfor %}

See also:

Post a Comment for "Passing Django Queryset In Views To Template"