Django:如何在一个类视图中引用另一个类视图的上下文变量
问题解决:在Leopard视图中获取Lion视图的上下文变量"Elephant"
先指出你现有代码的核心问题:
- Lion类的
get_context_data方法里,context super().get_context_data()缺少赋值符号,正确写法应为context = super().get_context_data(**kwargs) - Leopard类直接调用
Lion.get_context_data(context[“Elephant”])完全错误——get_context_data是实例方法,不能直接通过类调用,且此时context变量根本未定义,必然触发KeyError。
下面提供几种可行的实现方式:
方式一:提取公共逻辑到独立方法
把生成"Elephant"的逻辑抽离出来,让两个视图类都能复用:
class Lion(ListView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["Elephant"] = self._get_elephant_data() context["Giraffe"] = Eagle return context def _get_elephant_data(self): # 这里写入生成Rhinoceros的具体逻辑 return Rhinoceros class Leopard(ListView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # 实例化Lion后调用其公共方法获取数据 lion_view = Lion() context["Buffalo"] = lion_view._get_elephant_data() return context
方式二:使用Mixin类(推荐)
如果多个视图都需要用到该逻辑,用Mixin实现代码复用更优雅:
class ElephantContextMixin: def get_elephant_context(self): # 这里写入生成Rhinoceros的具体逻辑 return Rhinoceros class Lion(ListView, ElephantContextMixin): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["Elephant"] = self.get_elephant_context() context["Giraffe"] = Eagle return context class Leopard(ListView, ElephantContextMixin): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["Buffalo"] = self.get_elephant_context() return context
方式三:跨请求传递数据(仅特殊场景使用)
如果"Elephant"的数据需要在两个独立请求间传递,可使用会话(session)或缓存:
class Lion(ListView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) elephant_data = Rhinoceros context["Elephant"] = elephant_data # 存入session,注意数据需可序列化 self.request.session["elephant"] = elephant_data return context class Leopard(ListView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # 从session中读取数据 context["Buffalo"] = self.request.session.get("elephant") return context
这种方式仅适用于需要跨请求保留数据的场景,普通优先使用前两种方法。
内容的提问来源于stack exchange,提问作者Condado
相关产品推荐
相关产品推荐

