How can I send data to a base template in Django?
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 wou开发者_如何学Pythonld 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?
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 %}
...
精彩评论