hello I want to list my categories in navbar from database but the navbar is a partial view and I included my navbar in base.html . how can i give the data to this navbar
this is base.html that i included the partial view:
<body>
{% include "includes/navbar.html" %}
</body>
this is partial view:
<nav >
<div >
<a href="#">TechNerd</a>
<button aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"
data-bs-target="#navbarSupportedContent" data-bs-toggle="collapse" type="button">
<span ></span>
</button>
<div id="navbarSupportedContent">
<ul >
<li >
<a href="{% url 'post:posts' %}">Posts</a>
</li>
<li >
<a aria-expanded="false" data-bs-toggle="dropdown" href="#"
id="navbarDropdown" role="button">
categories
</a>
<ul aria-labelledby="navbarDropdown" >
<li><a href="#">Action</a></li>
<li><a href="#">Action</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
CodePudding user response:
With Context Processors you can pass data to template. So, can use them every .html page.
your_project/context_processors.py
from .models import Category
def category_list(request):
return {
"category_urls": [
{"name": category.name, "url": category.get_absolute_url()}
for category in Category.objects.all()
]
}
in settings.py
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [str(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",
"my_app.context_processors. category_list"
],
},
},
]
in base.html
{% for category in category_urls %}
<a href="{{category.url}}">{{category.name }}</a>
{% endfor %}
CodePudding user response:
You can use a custom context processor
to add data to the template context for every request.
# myapp/context_processors.py
from .models import Category
def catgories(request):
return {
"categories": Category.objects.all()
}
# settings.py
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
# ...your other settings....
"OPTIONS": {
"context_processors": (
"django.contrib.auth.context_processors.auth",
# ...other processors you use
"myapp.context_processors.categories",
),
},
}
]
# my_template.html
{% for category in categories %}
{{ category.name }}
{% endfor %}
CodePudding user response:
You can build your own context processor where it will be run with each request and pass the data from there. You will find a detailed answer in this link (Django variable in base.html).