html inside layouts and i make extends in other pages, all work fine but category menu (come from database) is hidden in some pages and i can see it just in one pages there is my code :
def produit_list(request):
produits = Produits.objects.all()
categories = Category.objects.all()
context = {
'produits':produits,
'categories':categories,
}
return render(request, 'shop.html', context)
#categories.html
<div >
<h2 >Categories</h2>
<ul >
{% for cat in categories %}
<li><a href="#">{{cat.name}}</a></li>
{% endfor %}
</ul>
</div>
i include this code inside base.html
i want know how to load it in all website like menu in bottom of every page, now i can see it just in shop.html.
Thank you
CodePudding user response:
Do it through a context processor
# Create a context_processors.py in your django app
def produit_list(request):
produits = Produits.objects.all()
categories = Category.objects.all()
context = {
'produits':produits,
'categories':categories,
}
# Return a dictionary with the data you want to load
# on every request call or every page.
return context
And in your settings:
# ...
TEMPLATES = [
{
# ...
"OPTIONS": {
"context_processors": [
# ...
"your_app.context_processors.produit_list",
# ...
],
},
}
]
# ...
Then you can call produits and categories on every page you want, just like you are doing it in your categories.html
CodePudding user response:
you can do this with a custom context processor or with custom template tags.
1- pass it through custom context processor
create a custom context processor file and a function.
# the custom_context.py file
def global_ctx():
return {
# any other values ...
"categories": Category.objects.all(),
}
add this file in your settings.py
file under the TEMPLATES
section as
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR / "templates"],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
"App_Name.custom_context.global_ctx", # Custom Context Processor
],
},
},
]
and you are good to go, you can access the categories
in all of your template files.
2- pass it through custom tags
under your app create a templatetags
directory. and create your custom tag file inside.
# the your_app/templatetags/custom_tag.py file
from django import template
register = template.Library()
@register.simple_tag
def get_categories():
return Category.objects.all()
then in your html
file, first load the custom tag {% load custom_tag %}
then you can access it.
this could help you more on custom template tags and filters.
CodePudding user response:
Thank you i will try this answer