9.2. Dynamic filtered content

To filter page content by category, we will add a condition to the store function in views.py. When a user navigates to a category page, we retrieve the category name using category__name and use it to filter the product query. This way, only products from the selected category are displayed, based on the category information obtained from the page's banner or URL parameters.

views.py
def store(request, category_name = None):
    products = Product.objects.filter(active=True) #? grabbing all products from the database (queryset, result of the search of the database)
    if category_name:
        products = products.filter(category__name = category_name) #? gets the name atribute from the category class and filters it according to the name of the category obtained from the banner
For example, when typing the url 'store/masculine' only the products on the masculine category will be displayed

The next step involves adding the hyperlinks to the banners. This will enable users to click on the banners and be redirected to the corresponding category pages.

homepage.html
{% for banner in banners %}
<a href="{% url 'store' banner.link_output %}">
    <img src = "{{ banner.image.url}}">
</a>
{% endfor %}
After clicking on the 'secret-friend' banner, we are directed to the 'secret-friend' category page inside the store url. (It is empty as currently there are no products in the 'secret-friend' category).

Last updated