How can I make the main category page?

Question:

Greetings! I have the following code:

urls.py

re_path(r'^category/(?P<hierarchy>.+)/$', show_category, name='category'),

views.py

def show_category(request, hierarchy=None):
    category_slug = hierarchy.split('/')
    parent = None
    root = Categories.objects.all()

for slug in category_slug[:-1]:
    parent = root.get(parent=parent, slug=slug)

try:
    instance = Categories.objects.get(parent=parent, slug=category_slug[-1])
except:
    instance = get_object_or_404(Goods, slug=category_slug[-1])
    return render(request, "shop/product.html", {'instance': instance})
else:
    return render(request, 'shop/categories.html', {'instance': instance})

The category model has the structure:
id, slug, imagePath, parent

I googled a lot and didn’t find a good answer to my question. Please help, this script displays only categories at localhost/category/(name of the parent category) and one level higher. And the problem is that I can’t make the main category page at all (localhost/category), please help or point me in the right direction to solve this issue!

I’m going crazy trying to solve this problem. Tried and google and dig into the documentation. Can’t decide at all.

Asked By: Nikita Mikheev

||

Answers:

If you adjust your regexp to

re_path(r'^category/(?P<hierarchy>.*)$', show_category, name='category'),

it will also match just category/.

You can then edit your view to something like

def show_category(request, hierarchy=None):
   hierarchy = (hierarchy or "").strip("/")
   if hierarchy:
       category_slug = hierarchy.split('/')
       parent = None
       for slug in category_slug[:-1]:
           parent = Categories.objects.get(parent=parent, slug=slug)
       category = Categories.objects.get(parent=parent, slug=category_slug[-1])
   else:
       category = None
       
   if category:
       return render(request, 'shop/categories.html', {'instance': category})
   # No category, show top-level content somehow
   return ...
Answered By: AKX
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.