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.
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.
{% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
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.
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.
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",
)
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