9.1. Dynamic filtered links

Active filter

The initial filter we'll apply is within the homepage and store functions in views.py. Instead of retrieving all records (previously using Banner.objects.all()), we will modify the queries to only fetch banners and products set to active on the admin page. The updated code for this will look like this:

views.py
def homepage(request):
    banners = Banner.objects.filter(active=True)
    
def store(request, category_name = None):
    products = Product.objects.filter(active=True) 

Now, since we want to enter a url in the store containing only a specific category, we will need to create it on the store urls.py file using the following syntax:

store\urls.py
path('store/<str:category_name>', store, name="store"), #? comes after the fixed urls, allows to create multiple urls with varied names

The category URL will derive from the main store URL, with the specific endpoint determined by the variable category_name. This variable, a string, will be obtained when a user clicks on a banner, enabling dynamic routing based on the selected category.

Important Note: When defining dynamic URLs, it's crucial to create them after their fixed counterparts in the URL configuration. In this case, the dynamic URL that uses the category_name variable should be added only after the main 'store/' URL has been defined. This ordering ensures that the base URL structure is established before introducing variations based on dynamic content.

In the views.py file, we'll pass the category_name variable as a parameter to the store function, initially set to None. This setup is essential because, as previously mentioned, all dynamic category URLs will originate from the main store URL.

views.py
def store(request, category_name = None):

Last updated