You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django视图中get_context_data与get方法无法协同工作如何解决

问题根因

你重写get方法后直接返回了仅携带表单变量的渲染响应,完全没有调用get_context_data方法,所以模板无法获取get_context_data中定义的酒店照片、房型等上下文变量,自然会出现变量不存在的各类报错。

修复方案

推荐你将表单实例化逻辑合并到get_context_data中,无需单独重写get方法,符合Django基于类视图的设计规范:

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)
    # 直接在此处实例化表单,通过self.request获取session参数
    context['book_a_room_form'] = BookARoomForm(initial={'arrival_date': self.request.session['arrival_date']})
    # 优化查询逻辑,避免重复查询酒店对象
    hotel = AmericanHotel.objects.filter(slug=self.kwargs.get('slug')).first()
    context['hotel_extra_photos'] = AmericanHotelPhoto.objects.filter(title=hotel.id)
    context['room_type'] = RoomType.objects.filter(title=hotel.id)
    return context

如果你坚持要保留单独的get方法写法,需要调用get_context_data合并上下文:

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)
    hotel = AmericanHotel.objects.filter(slug=self.kwargs.get('slug')).first()
    context['hotel_extra_photos'] = AmericanHotelPhoto.objects.filter(title=hotel.id)
    context['room_type'] = RoomType.objects.filter(title=hotel.id)
    return context

def get(self, request, *args, **kwargs):
    # 先获取原有上下文
    context = self.get_context_data(*args, **kwargs)
    # 把表单添加到上下文里
    context['book_a_room_form'] = BookARoomForm(initial={'arrival_date': request.session['arrival_date']})
    # 传入完整上下文渲染
    return render(request, self.template_name, context)

额外优化说明:原有代码重复调用同一条酒店查询语句多次请求数据库,调整为单次查询存储为变量后复用,可减少不必要的数据库请求,提升性能。

内容的提问来源于stack exchange,提问作者Ross Symonds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 08:24:03