Let's say I have a django site, and a base template for all pages with a footer that I want to display a list of the top 5 products on my site. How would I go about sending that list to the base template to render? Does every view need to send that data to the render_to_response? Should I use a template_tag? How would you do it?
+3
A:
You should use a custom context processor. With this you can set a variable e.g. top_products
that will be available in all your templates.
E.g.
# in project/app/context_processors.py
from app.models import Product
def top_products(request):
return {'top_products': Products.objects.all()} # of course some filter here
In your settings.py
:
TEMPLATE_CONTEXT_PROCESSORS = (
# maybe other here
'app.context_processors.top_products',
)
And in your template:
{% for product in top_products %}
...
Felix Kling
2010-02-14 23:25:38
I'll give that a try. It sounds just like what I was looking for.
Ryan Montgomery
2010-02-15 01:10:41