我曾經有過 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,
})
uj5u.com熱心網友回復:
你應該在 get 中呼叫 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']})
context = self.get_context_data( *args, **kwargs)
context['book_a_room_form'] = book_a_room_form
return render(request, self.template_name, context=context)
uj5u.com熱心網友回復:
感謝 Mohamed Beltagy 的指導。
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/365355.html
標籤:Python 姜戈 django-views django-forms
