Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Model Data from Django Base Template

I have a model Category, and I want its objects to always be displayed in a navigation menu in my base.html template (which all of my other templates extend).

I want to learn best-practices so would like to know what the correct/accepted way of providing this data to the template is.

like image 931
johnrees Avatar asked Oct 10 '10 14:10

johnrees


People also ask

How do I access Django templates?

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 {% mean in Django?

{% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What does Django template contains?

Being a web framework, Django needs a convenient way to generate HTML dynamically. The most common approach relies on templates. A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted.

What is base template in Django?

A template is a text file that defines the structure or layout of a file (such as an HTML page), it uses placeholders to represent actual content. A Django application created using startapp (like the skeleton of this example) will look for templates in a subdirectory named 'templates' of your applications.


1 Answers

Use a custom context processor:

In context_processors.py:

def categories(request):
    return {
        'categories': Categories.objects.all()
    }

And add it to your settings.py:

TEMPLATE_CONTEXT_PROCESSORS = (
    # ... django's default context processors
    "your_app.context_processors.categories", 
)
like image 159
asafge Avatar answered Sep 19 '22 04:09

asafge