Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 747
rmontgomery429 Avatar asked Feb 14 '10 23:02

rmontgomery429


People also ask

How can I pass data to Django layouts like base HTML ') without having to provide it through every view?

Use a context processor, which is made exactly for that purpose.

How do you pass variables from Django view to a template?

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.

How do you call a template in Django?

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.

What does {% include %} do in Django?

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.


1 Answers

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 %}
    ...
like image 81
Felix Kling Avatar answered Nov 15 '22 00:11

Felix Kling