Django mptt, extends “base.html”

为君一笑 提交于 2021-02-10 07:49:09

问题


In base.html:

<div id="menu_shop">
            <input name="search" placeholder="search">
            <p>Category:</p>
             {% 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>
</div>

in views:

def show_category_tree(request):
    return render_to_response("base.html",
                              {'nodes': Category.tree.all()},
                              context_instance=RequestContext(request))

urls.py:

url(r'^category/', 'item.views.show_category_tree'),
url(r'^category/(?P<slug>[\w\-_]+)/$', 'item.views.by_category'),

How to display this in "by_category.html"

If I try(for example):

{% extends "base.html" %}


{% block content %}
{% for e in entries %}
<p><b>{{ e.name}}</b></p>

<p>{{ e.desc}}</p>
{% endfor %}

{% endblock %}

I have this error:

http://dpaste.com/810809/

{% extends "base.html" %} does not work. If I remove it, everything works.


回答1:


You are seeing this error because your template context for the by_category does not include nodes.

The extends tag is related to the template, not the view. It makes your by_category.html template extend the base.html template, but it does not include the template context from any other view.

The easiest fix would be to add nodes to your template context in the by_category view.

def by_category(request, slug):
    entries = Entry.objects.filter(...)
    return render_to_response("base.html",
        {'entries': entries,
         'nodes': Category.tree.all()},
        context_instance=RequestContext(request))

This would be repetitive if you want to display the nodes in lots of other views. If you want to include the nodes in all views, you may want to write a request context processor. If you want to include it in some but not all pages, then try writing a custom template tag.



来源:https://stackoverflow.com/questions/12769145/django-mptt-extends-base-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!