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?
Use a context processor, which is made exactly for that purpose.
And this is rather simple, because Django has built-in template modules that makes a transfer easy. Basically you just take the variable from views.py and enclose it within curly braces {{ }} in the template file.
To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.
The include tag allows you include a template inside the current template. This is useful when you have a block of content that are the same for many pages.
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 %}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With