2017-09-21 40 views
0

你能幫我解決這個問題嗎?我想添加只顯示轉換的菜單標題。而將此代碼添加到我的標籤文件:w d django列表索引超出範圍

@register.inclusion_tag('home/tags/top_menu.html', takes_context=True) 
def top_menu(context, parent, calling_page=None): 
    request = context['request'] 
    language_code = request.LANGUAGE_CODE 
    menuitems = parent.get_children().live().in_menu().filter(title = language_code)[0].get_children() 
    for menuitem in menuitems: 
     menuitem.show_dropdown = has_menu_children(menuitem) 
     menuitem.active = (calling_page.path.startswith(menuitem.path) 
          if calling_page else False) 
    return { 
     'calling_page': calling_page, 
     'menuitems': menuitems, 
     'request': context['request'], 
    } 

但我正在逐漸頁面上此錯誤: 列表索引超出範圍,並突出顯示的代碼

{%top_menu父= site_root calling_page =自% }

使用鶺鴒1.12和Python 3.6.2

回答

2

parent.get_children().live().in_menu().filter(title = language_code)[0]

您不會考慮.filter(title = language_code)返回空列表的可能性。

您應該使用try-except或將這部分代碼分成幾行,然後檢查.filter是否返回空列表。

例如:

@register.inclusion_tag('home/tags/top_menu.html', takes_context=True) 
def top_menu(context, parent, calling_page=None): 
    request = context['request'] 
    language_code = request.LANGUAGE_CODE 
    try: 
     menuitems = parent.get_children().live().in_menu().filter(title = language_code)[0].get_children() 
    except IndexError: 
     menuitems = [] 
    else: # you don't actually need to have 'else' in this case 
     for menuitem in menuitems: 
      menuitem.show_dropdown = has_menu_children(menuitem) 
      menuitem.active = (calling_page.path.startswith(menuitem.path) 
           if calling_page else False) 
    return { 
     'calling_page': calling_page, 
     'menuitems': menuitems, 
     'request': context['request'], 
    }