【问题标题】:How to display child element in Django MPTT?如何在 Django MPTT 中显示子元素?
【发布时间】:2022-01-03 17:27:08
【问题描述】:

我正在尝试调用模型的父子元素,我已经阅读了 MPTT 模型文档。我按照文档中的说明做了,但是我的模板无法打印孩子

这个问题的可能原因是什么?

这是我的观点:

def category_view(request):
category = Categories.objects.all()
brands = Brands.objects.all()
context ={
    'category':category,
    'brands':brands,
       
            
}
return render(request,'./ecommerce/categories.html', context)

这是我的模板 HTML:

{% load mptt_tags %}
     {% recursetree category%}
        <div class="category-wrap mb-4">
            <div class="category category-group-image br-sm">
                <div class="category-content">
                    <h4 class="category-name"><a href="">{{ node.name }}</a>
                    </h4>
                    
                    <ul class="category-list">
                        {% if not node.is_leaf_node %}
                        <li><a href="">{{children}}</a></li>
                        {% endif %}
                       
                    </ul>
                    
                </div>
                
            </div>
        </div>
        <!-- End of Category Wrap -->
        
        {% endrecursetree %}

打印父元素,但不打印子元素

【问题讨论】:

  • 我认为问题在于您如何编写{{children}} 标签。大括号前后需要留空格,如{{ children }}
  • 我认为不应该这样。
  • 它就在文档中。
  • 是的,但它不是那样工作的。我认为我们应该用 get_children() 实例方法编写查询集,你知道吗?

标签: django django-mptt


【解决方案1】:

做了很多尝试,通用方法解决了我的问题。其他有类似问题的人可以从我的回答中受益,因此发布解决方案。

观看次数:

category = Categories.objects.filter(parent=None)

模板:

{% for category in categories %}
        <div class="category-wrap mb-4">
            <div class="category category-group-image br-sm">
                <div class="category-content">
                    <h4 class="category-name"><a href="{% url 'ecommerce:item_by_category' category.slug|slugify %}">{{ category.name }}</a>
                    </h4>
                    
                    <ul class="category-list">
                        {% for cat in category.get_children %}              
                        <li><a href="/categories/{{ cat.id }}/">{{  cat.name }}</a> </li> 
                        {% endfor %}
                        
                      
                       
                        
                       
                    </ul>
                    
                </div>
                
            </div>
        </div>
        <!-- End of Category Wrap -->
        
        {% endfor %}

【讨论】:

    猜你喜欢
    • 2013-12-05
    • 2012-05-23
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 2020-07-28
    • 1970-01-01
    • 2012-07-15
    相关资源
    最近更新 更多