2014-12-06 65 views
0

我在view.py以下陣列比較值

chapter = 5 
number_of_chapters = 5 
selected_chapters = list() 
for index in range(1, number_of_chapters+1): 
    selected_chapters.append(index) 
return render(request, 'verses.html', {'chapter': chapter, 'selected_chapters': selected_chapters}) 

但是當我嘗試在此列表chapter比較條目它永遠不會返回true

模板

<select name="c" id="chapter" value="{{ chapter }}" onchange="bible_search(true);"> 
    <option value="1">Chapter</option> 
    {% for c in selected_chapters %} 
     <option {% if c == chapter %} selected {% endif %} value="{{ c }}">{{ c }}</option> 
    {% endfor %} 
</select> 

我想知道如果我需要將字符串轉換爲int或某處?

回答

0

似乎你還沒有發佈完整的代碼,因爲這對我來說工作得很好。使用您提供的代碼,當我導航到從該視圖呈現的頁面時,我看到select的值爲5。我想這就是你想要的?這表明在視圖或模板的其他地方存在一些衝突。

雖然我們在這裏,但HTML select元素沒有value屬性,因此應該將其刪除。其次,您有兩個option元素具有相同的值。這是在瀏覽器中呈現的HTML。

<select name="c" id="chapter" value="5" onchange="bible_search(true);"> 
    <option value="1">Chapter</option> 
    <option value="1">1</option> 
    <option value="2">2</option> 
    <option value="3">3</option> 
    <option value="4">4</option> 
    <option selected="" value="5">5</option> 
</select> 
+0

我的代碼和我給出的示例之間唯一的區別在於章節的數量是從數據庫中檢索的。這是我需要將其轉換爲int的地方。它現在有效。 – Jon 2014-12-07 15:05:47