我正在尝试为Django 1.8中的视图编写单元测试。 我正在尝试测试一个包含年份和月份作为参数的地址的视图。 这是我的观点地址:
url(r'^/(?P<year>[0-9]{4})/(?P<month>[0-9]+)$', views.BookingListView.as_view(), name="list"),
这是我的测试代码:
def test_booking_list(self):
url = reverse('archive:list', kwargs={'year': 2011, 'month': 10})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
我收到了一个错误:
Traceback (most recent call last):
File "path to.../test_views.py", line 16, in test_booking_list
self.assertEqual(response.status_code, 200)
AssertionError: 404 != 200
修改
浏览器栏中的观看路径:http://127.0.0.1:8000/en/archive/2011/01
查看BookingListView:
class BookingListView(ListView, MonthArchiveView):
queryset = models.Booking.objects.order_by('-date_start')
template_name = 'archive/booking_list.html'
date_field = 'date_start'
def get_context_data(self, **kwargs):
min_year = self.queryset.aggregate(Min('date_start'))
max_year = self.queryset.aggregate(Max('date_start'))
months_choices = []
for i in range(1, 13):
months_choices.append({'number': i, 'name': _(calendar.month_name[i])})
context = super(BookingListView, self).get_context_data(**kwargs)
context['mode'] = 'archive'
context['years'] = range(min_year['date_start__min'].year, max_year['date_start__max'].year + 1)
context['months'] = months_choices
context['selected_year'] = self.kwargs['year']
context['selected_month'] = self.kwargs['month']
context['object_list'] = models.Booking.objects.filter(date_start__year=self.get_year(),
date_start__month=self.get_month())
context['current_month_name'] = _(calendar.month_name[int(self.kwargs['month'])])
return context