2017-09-11 43 views
1

我有以下模板:Django的模板不輸出值,以HTML表格單元格

<table> 
    <tr> 
     <th>Monday</th> 
     <th>Tuesday</th> 
     <th>Wednesday</th> 
     <th>Thursday</th> 
     <th>Friday</th> 
     <th>Saturday</th> 
     <th>Sunday</th> 
    </tr> 

    {% for row in table %} 
    <tr> 
     {% for i in week_length %} 
     <td>{{row.i}}</td> 
     {% endfor %} 
    </tr> 
    {% endfor %} 
</table> 

而以下幾種觀點:

def calendar(request): 
    template_name = 'workoutcal/calendar.html' 

    today_date = timezone.now() 
    today_year = today_date.year 
    today_month = today_date.month 
    today_day = today_date.day 

    table = maketable(today_date) # Creates something like: [[None, 1, 2, 3, 4, 5, 6],[7, 8, ...],...,[28, 29, 30, 31, None, None, None]] 

    template = loader.get_template('workoutcal/calendar.html') 

    #Workout.objects.filter("Workouts lie between certain dates") 
    context = { 
     'workout_list': Workout.objects.filter(date__year = today_year, date__month = today_month, date__day = today_day), 
     'table': table, # The calendar 
     'week_length': range(7), 
    } 
    return HttpResponse(template.render(context, request)) 

當我訪問該頁面(localhost:8000/workoutcal),沒有什麼不同之處輸出表格標題。它看起來像這樣:

The table

inspecting the object

我想不通爲什麼Django是不是把我的輸出進入細胞。我不想爲列表中的元素輸出None,然後簡單地爲所有其他元素輸入元素內容(全部是字符串)。有任何想法嗎?

+1

你想通過'{{row.i}}'看到什麼? –

回答

3

你正在迭代錯誤的東西。您的日曆是列表清單;您應該迭代每行,然後遍歷該行中的每一列。 week_length是完全不相關的。

{% for week in table %} 
<tr> 
    {% for day in week %} 
    <td>{{ week }}</td> 
    {% endfor %} 
</tr> 
{% endfor %} 
0

您沒有正確訪問row對象中的項目。它們的索引號爲i而不是名爲i的屬性。

你可以只做到以下幾點:

{% for i in row %} 
    <td>{{ i }}</td> 
{% endfor %} 

因爲row是您要訪問的元素列表。這將避免需要通過week_length變量。