我尝试使用视图来创建一个表(我后来想用数据填充它)。但是,如果我打开相应的网址,视图会创建一个"名称' context'没有定义"错误。谁能解释一下?
def room_overview(request, year, month):
rooms = Room.objects.all()
long_month = ['01', '03', '05', '07', '08', '10', '12']
short_month = ['04','06','09','11']
if month in long_month:
month_max = 31
elif month in short_month:
month_max = 30
elif year % 4 == 0 and year %100 != 0 or year % 400 == 0:
month_max = 29
else:
month_max = 28
days = []
for i in range(1, month_max + 1):
days.append(str(i))
context['rooms'] = rooms
context['days'] = days
context['month'] = month
context['year'] = year
return render(request, 'hotel/overview.html', context)
视图的模板如下所示:
<h2>Overview {{month}}/{{year}}:</h2>
<div class="overview">
<table class="table table-condensed">
<tr>
{% for day in days %}
<th>day</th>
{% endfor %}
</tr>
{% for room in rooms %}
<tr>
<td>{{ room.name }}</td>
{% for day in days %}
<td> 1 </td>
{% endfor %}
</tr>
{% endfor %}
</table>
</div>
这是网址:
url(r'^room/overview/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$',views.room_overview, name='room_overview'),
答案 0 :(得分:0)
在添加键/值对之前,必须先定义上下文变量。
你可以这样做:
context = {}
context['rooms'] = rooms
context['days'] = days
context['month'] = month
context['year'] = year
或者,我个人喜欢的方式:
context = {
'rooms': rooms,
'days': days,
'month': month,
'year': year,
}
这将解决您的错误。