15.2. Personalized 'context' variable

The items in the cart will need to be visible and accessible on all pages, necessitating their inclusion within the context of all view functions.

To facilitate this integration, we will generate a new file within the store directory titled new_context.py. This file will contain values that need to be accessed by all html files.

Within new_context.py, we will define a function named cart whose return value, the amount of products inside it, will be made accessible to all other HTML files.

new_context.py
def cart(request) :
    product_amount_cart = 2 #? for testing, value has to be over 0
    return {"product_amount_cart" : product_amount_cart}

This phenomenon arises due to the inclusion of a component called context_processors within the templates list of the settings.py file.

settings.py
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',
            ],
        },
    },
]

This module discerns the universal attributes shared across all templates irrespective of the specific view context. Such attributes encompass debugging messages/settings, request methodologies, and user authentication configurations.

Incorporated after the last element of the list, there will be a reference to the recently implemented cart function, ensuring its universal accessibility across all HTML files.

settings.py
'store.new_context.cart',

Finally, within the navbar.html file, insert the { % load static %} directive at the beginning. This step is imperative as we intend to include a cart image within the navbar sourced from the static folder.

On the line immediately preceding the closing <\nav> tag, insert the code {{ product_amount_cart }}. This addition will ensure the display of the quantity of items in the cart on every page.

navbar.html
{% 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 }}
</nav>
Now the cart image and the product amount are displayed amongst all pages

Last updated