我有这个用于分页上下文的ListView,但是我想在上下文中添加汽车类型,为此,我需要在json中构建它,我不知道如何,或者是否有其他解决方法,任何帮助将不胜感激。
class CarListView(ListView):
model = Car
template_name = 'listings.html'
context_object_name = 'cars'
ordering = ['-created']
paginate_by = 5
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
print(context)
paginator = context['paginator']
page_numbers_range = 10 # Display 5 page numbers
max_index = len(paginator.page_range)
page = self.request.GET.get('page')
print(self.request)
current_page = int(page) if page else 1
start_index = int((current_page - 1) / page_numbers_range) * page_numbers_range
end_index = start_index + page_numbers_range
if end_index >= max_index:
end_index = max_index
page_range = paginator.page_range[start_index:end_index]
# context['page_range'] = page_range
# return context
cars = Car.objects.all()[:10]
car_types = CarType.objects.all()
context = {'cars': cars, 'car_types': car_types}
return context
答案 0 :(得分:0)
您要在上一条语句中覆盖整个上下文。...
更改
context = {'cars': cars, 'car_types': car_types}
为
context['cars']=cars
context['car_types']=car_types