[英]How can I make the main category page?
问候! 我有以下代码:
网址.py
re_path(r'^category/(?P<hierarchy>.+)/$', show_category, name='category'),
视图.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})
类别 model 具有结构: id, slug, imagePath, parent
我用谷歌搜索了很多,并没有找到一个很好的答案来回答我的问题。 请帮助,此脚本仅显示 localhost/category/(父类别的名称)和更高级别的类别。 问题是我根本无法制作主类别页面(localhost/category) ,请帮助或指出正确的方向来解决这个问题!
我要疯了,试图解决这个问题。 尝试和谷歌并深入研究文档。 根本无法决定。
如果您将正则表达式调整为
re_path(r'^category/(?P<hierarchy>.*)$', show_category, name='category'),
它也将只匹配category/
。
然后,您可以将视图编辑为类似
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 ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.