呈现页面时的NoReverseMatch

时间:2017-01-20 22:05:27

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

我似乎知道问题的位置,因为我可以绕过它,但为了绕过它,我必须牺牲一个我真正想要保留的功能。

以下是处于非工作状态的相关代码:

{% if sections %}

        {% for item in sections %}

            <a class="sections" href="{% url 'sections:generate' item.section.slug %}">{{ item.section.title }}</a>

            {% for subsection in item.subsections %}

                <p>{{ subsection.title }}</p>

            {% endfor %}

        {% endfor %}

    {% else %}

        <p>Error retrieving sections or no sections found</p>

    {% endif %}

上面的问题部分在链接标记中。让我通过显示相关的view.py来解释:

def index(request):
    sections = Section.objects.all()
    context = {
        'sections': [],
    }

    for section in sections:
        context.get("sections").append(
            {
                'section': section,
                'subsections': get_subsections(section),
            }
        )

    return render(request=request, template_name='index.html', context=context)

所以,&#39;部分&#39;是一个可迭代的项目列表,包含每个项目带有两个条目的字典。一,&#39;部分&#39;和一个小节&#39;。每个部分都有多个小节,这是我真正想要完成的。

通常情况下,当不打扰子部分并简单地迭代部分列表时工作正常。该模板代码如下所示:

{% for section in sections %}

    <a href="{% url 'sections:generate' section.slug %}">{{ section.title }}</a>

{% endfor %} 

请注意!上面的代码工作得很好!但是,只要我添加&#39;部分&#39;作为字典列表,必须通过item.section.slug引用slug页面停止渲染。

请告知。

1 个答案:

答案 0 :(得分:1)

尝试使用元组:

查看:

context['sections'] = [(section, tuple(get_subsections(section))) for section in sections]

模板:

{% for section, subsections in sections %}
    <a class="sections" href="{% url 'sections:generate' section.slug %}">{{ section.title }}</a>
    {% for subsection in subsections %}
        <p>{{ subsection.title }}</p>
    {% endfor %}
{% endfor %}