Передача контекста из get_conext_data в get
Раньше у меня book_a_room_form = BookARoomForm()
был в get_context_data
, но потом я изменил его на book_a_room_form = BookARoomForm(initial={'arrival_date': request.session['arrival_date']})
и поместил в get
(см. причину перемещения его в get
здесь). get_context_data
и get
работают по отдельности. Но я не могу заставить их работать вместе. Я прочитал десятки сообщений по этому вопросу, просмотрел свой трассировочный маршрут и получил множество различных сообщений об ошибках. Теперь я просто хожу по кругу с этой проблемой.
def get_context_data(self, *args, **kwargs):
context = super(HotelDetailSlugView, self).get_context_data(*args, **kwargs)
cart_obj, new_obj = Cart.objects.new_or_get(self.request)
context['hotel_extra_photos'] = AmericanHotelPhoto.objects.all().filter(title=AmericanHotel.objects.all().filter(slug=self.kwargs.get('slug'))[0].id)
context['room_type'] = RoomType.objects.all().filter(title=AmericanHotel.objects.all().filter(slug=self.kwargs.get('slug'))[0].id)
return context
def get(self, request, *args, **kwargs):
# This code is executed each time a GET request is coming on this view
# It's is the best place where a form can be instantiate
book_a_room_form = BookARoomForm(initial={'arrival_date': request.session['arrival_date']})
return render(request, self.template_name, {'book_a_room_form': book_a_room_form,
})
вы должны вызывать контекст внутри get
def get(self, request, *args, **kwargs):
# This code is executed each time a GET request is coming on this view
# It's is the best place where a form can be instantiate
book_a_room_form = BookARoomForm(initial={'arrival_date': request.session['arrival_date']})
context = self.get_context_data( *args, **kwargs)
context['book_a_room_form'] = book_a_room_form
return render(request, self.template_name, context=context)
Спасибо Мохамеду Белтаги за ваши рекомендации.
def get(self, request, *args, **kwargs):
# This code is executed each time a GET request is coming on this view
# It's is the best place where a form can be instantiate
book_a_room_form = BookARoomForm(initial={'arrival_date': request.session['arrival_date']})
# get_context_data(**kwargs) - ¶
# Returns context data for displaying the object.
# The base implementation of this method requires that the self.object attribute be set by the view (even if None).
# Be sure to do this if you are using this mixin without one of the built-in views that does so.
self.object = self.get_object() # assign the object to the view
context = self.get_context_data( *args, **kwargs)
context['book_a_room_form'] = book_a_room_form
return render(request, self.template_name, context=context)