【问题标题】:NoReverseMatch when rendering page渲染页面时 NoReverseMatch
【发布时间】:2017-06-06 00:01:39
【问题描述】:

我似乎知道问题出在哪里,因为我可以解决它,但为了解决它,我必须牺牲一个我真正想保留的功能。

这里是非工作状态下的相关代码:

{% 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)

因此,“sections”是一个可迭代的项目列表,每个项目都包含一个包含两个条目的字典。一个,“部分”和一个“小节”。每个部分都有多个小节,这是我真正想要完成的。

通常,当不打扰小节并简单地遍历节列表时,效果很好。其模板代码如下所示:

{% for section in sections %}

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

{% endfor %} 

注意!上面的代码工作得很好!但是,一旦我将“部分”添加为字典列表并且必须通过 item.section.slug 引用 slug,页面就会停止呈现。

请指教。

【问题讨论】:

  • 当你没有导致异常的 url 标签时会打印什么? (理想情况下也添加item.section.slug 进行渲染)

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


【解决方案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 %}

【讨论】: