2017-01-20 132 views
0

我似乎知道問題的位置,因爲我可以解決它,但爲了避開它,我必須犧牲一個我真正想要保留的函數。NoReverseMatch當呈現頁面

這裏是在非工作狀態的相關代碼:

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

所以,「節」是項目的迭代列表,包含每一個項目有兩個項目的字典。一,'章節'和一個'小節'。每個部分都有多個小節,這是我真正想要完成的。

通常情況下,當不打擾子節點,只是遍歷節的列表工作正常。該模板的代碼如下所示:

{% for section in sections %} 

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

{% endfor %} 

注意!上面的代碼工作得很好!但是,只要我將'sections'添加爲字典列表並且必須通過item.section.slug引用slug,頁面將停止呈現。

請指教。

+0

,當你不知道該網址的標籤引起異常什麼是印刷? (理想情況下,添加'item.section.slug'來渲染) – yummies

回答

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 %} 
+0

這工作,謝謝先生。 –