From 2a10df5510c19b7f42c9aae1de58b3774abc30b9 Mon Sep 17 00:00:00 2001 From: Orestes Sanchez Date: Thu, 31 Jul 2014 23:36:12 +0200 Subject: [PATCH 1/2] Check for all the categories in the path one by one, from the root to the leaf. Thanks to http://stackoverflow.com/questions/9492190/django-categories-sub-categories-and-sub-sub-categories --- categories/views.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/categories/views.py b/categories/views.py index 9d5d383d..ee06e309 100644 --- a/categories/views.py +++ b/categories/views.py @@ -20,15 +20,14 @@ def category_detail(request, path, template_name='categories/category_detail.html', extra_context={}): path_items = path.strip('/').split('/') - if len(path_items) >= 2: - category = get_object_or_404(Category, - slug__iexact=path_items[-1], - level=len(path_items) - 1, - parent__slug__iexact=path_items[-2]) - else: - category = get_object_or_404(Category, - slug__iexact=path_items[-1], - level=len(path_items) - 1) + categories = [] + parent = None + for slug in path_items: + category = get_object_or_404(Category, + slug__iexact=slug, + parent=parent) + categories.append(category) + parent = categories[-1] templates = [] while path_items: From 1ac652ab3284fc1d3065c29460e3989eb5e7d0ae Mon Sep 17 00:00:00 2001 From: Orestes Sanchez Date: Wed, 22 Nov 2017 20:31:45 +0100 Subject: [PATCH 2/2] Substitute slug to path calculation algorithm. --- categories/views.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/categories/views.py b/categories/views.py index ee06e309..51d9299a 100644 --- a/categories/views.py +++ b/categories/views.py @@ -23,8 +23,8 @@ def category_detail(request, path, categories = [] parent = None for slug in path_items: - category = get_object_or_404(Category, - slug__iexact=slug, + category = get_object_or_404(Category, + slug__iexact=slug, parent=parent) categories.append(category) parent = categories[-1] @@ -43,6 +43,11 @@ def category_detail(request, path, def get_category_for_path(path, queryset=Category.objects.all()): + path_items = path.strip('/').split('/') + for slug in path_items: + queryset = queryset.filter( + slug__iexact=slug) + """ path_items = path.strip('/').split('/') if len(path_items) >= 2: queryset = queryset.filter( @@ -53,6 +58,7 @@ def get_category_for_path(path, queryset=Category.objects.all()): queryset = queryset.filter( slug__iexact=path_items[-1], level=len(path_items) - 1) + """ return queryset.get()