25. Categories and types on the navigation bar
Currently, we apply filters by passing parameters to view functions, such as in the store(request, category_name=None)
function, which uses the category name to filter associated products.
For the navigation bar, we will explore an alternative method.
We will follow a similar procedure as in Chapter 15.2, where we added the cart
function inside the new_context.py
file to make its return value, product_amount_cart
, accessible across all HTML files.
In this instance, we will create a new function, category_types
, within the new_context.py
file. This function obtains all the categories and types currently present on the database and returns their values for use on the other templates.
First, include the Type
class via import in the new_context.py
file:
from .models import Order, OrderedItem, Client, Categoric, Type
def category_type(request) :
categories = Categoric.objects.all()
types = Type.objects.all()
return {"categories" : categories, "types" : types}
Important: As done in Chapter 15.2, ensure that the path to the function is added at the end of the TEMPLATES
list in the settings.py
file, so that Django recognizes it across all template files.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
'store.new_context.cart',
'store.new_context.category_type',
],
},
},
]
Finally, in the navbar.html
file, we will display the categories and their respective types. Each category and type will include filter links that navigate to the products associated with them.
{% load static %}
<nav>
<a href = "{% url 'homepage' %}">Reserva</a>
<a href = "{% url 'store' %}">Store</a>
<a href = "{% url 'login' %}">Login</a>
<a href = "{% url 'your_account' %}">My Account</a>
<a href = "{% url 'cart' %}">Cart</a>
<img src = "{% static 'images/cart.png' %}" width="30" height="30">
{{ product_amount_cart }}
<div style="display: flex;">
{% for category in categories %}
<div>
<a href="{% url 'store' %}{{ category.name }}">{{ category.name }}</a>
<br>
{% for type in types %}
<a href="{% url 'store' %}{{ category.name }}-{{ type.name }}">{{ type.name }}</a>
{% endfor %}
</div>
{% endfor %}
</div>
</nav>

Last updated