Home > Enterprise >  How can I make the main category page?
How can I make the main category page?

Time:08-06

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.g.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.

CodePudding user response:

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("/")  # Remove stray slashes
   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.g.html', {'instance': category})
   # No category, show top-level content somehow
   return ...
  • Related