显示层次结构中的类别和子类别

时间:2017-12-04 02:24:47

标签: python django django-models django-views django-mptt

我正在使用django-mptt作为类别模型。我想在屏幕截图中显示类别和子类别列表。我可以显示的方式是所有列表,没有任何结构,如下面

卧室项目

衣橱

2 PIECE ALMIRAH

3 PIECE ALMIRAH

BED

双倍低床

QUEEN SIZE LOW BED

这种方式很难知道哪一个是父类别,哪一个是子类别和大童类别等。我可以使用Category.objects.root_nodes()

显示上述方式或仅显示父类别

enter image description here

这是我的模型,视图和模板

class Category(MPTTModel):
    name = models.CharField(max_length=100, blank=True, null=True)
    image = models.ImageField(null=True, blank=True,
                              upload_to=upload_furniture_image_path)
    slug = models.SlugField(max_length=200, unique=True)
    parent = TreeForeignKey('self', null=True, blank=True,
                            related_name='children', db_index=True)


def furniture(request, slug):
    instance = get_object_or_404(Furniture, slug = slug)
    cart_obj, new_obj = Cart.objects.new_or_get(request)
    categories = Category.objects.all()
    context = {
        'furniture': instance,
        'cart': cart_obj,
        'categories': categories
    }
    return render(request, 'furnitures/furniture.html', context)




 <div class="panel-body">
      <ul class="nav nav-pills nav-stacked category-menu">
           {% for category in categories %}
              <li>{{category.name}}</li>
           {% endfor %}
       </ul>
  </div>

所以我的问题是如何将父类别和子类别分开,以便我可以在屏幕截图中显示?

以下是包含子女和子女的父类别

enter image description here

1 个答案:

答案 0 :(得分:1)

由于您使用的是MPTTModel,因此最佳解决方案是使用mptt方法遍历树。

如果要在模板中显示树结构,可能需要在mptt方法周围编写模板标签/过滤器,或者使用mptt库提供的标签/过滤器。

示例解决方案:

views.py

return render_to_response('furnitures/furniture.html',
                           {'nodes':Category.objects.all()}, 
                           context_instance=RequestContext(request))

模板:

<ul class="root">
    {% recursetree nodes %}
        <li>
            {{ node.name }}
            {% if not node.is_leaf_node %}
                <ul class="children">
                    {{ children }}
                </ul>

               {% endif %}
            </li>
        {% endrecursetree %}
    </ul>

详细解释here

相关问题