【问题标题】:Django-mptt not listing names in templatesDjango-mptt 未在模板中列出名称
【发布时间】:2024-05-23 09:25:01
【问题描述】:

我正在使用 django-mptt 库来构建类别树。当我把下面的代码放在我的模板中时,我得到了这个错误。

index.html

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

这是我得到的错误。

VariableDoesNotExist at /

Failed lookup for key [nodes] in [{'True': True, 'False': False, 'None': None}, {}, {}, {'listing': <TreeQuerySet [<Category: Clothes>, <Category: Children Clothes>, <Category: Mens Clothes>, <Category: Womens Clothes>, <Category: Electronics>, <Category: Foods>]>}]

view.py

定义索引(请求): Listing=Category.objects.all()

context={
    'listing':listing
}
return render(request,'catalog/index.html',context)

【问题讨论】:

    标签: python python-3.x django django-views django-templates


    【解决方案1】:

    您的模板变量的名称是listing,而不是nodes

    {% load mptt_tags %}
    <ul class="root">
        {% recursetree listing %}
            …
        {% endrecursetree %}
    </ul>

    【讨论】: