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

如何在基于类的视图中通过get_object函数向模板传递上下文?

在Django基于类的视图中传递额外上下文(含get_object场景)

你当前的代码里,在get_object方法中定义的context不会被传递到模板——因为get_object的职责只是返回视图要展示的核心对象,而非处理上下文数据。要给模板传递自定义上下文,正确做法是重写get_context_data方法,结合你已有的get_object逻辑,修改后的代码如下:

class DetailMessages(LoginRequiredMixin, DetailView, ChannelFormMixin):
    template_name = 'DM/chat.html'

    def get_object(self, *args, **kwargs):
        my_username = self.request.user.username
        username = self.kwargs.get("username")
        channel, _ = Channel.objects.get_dm_channel(my_username, username)
        if channel is None:
            raise Http404
        return channel

    def get_context_data(self, **kwargs):
        # 先获取父类生成的默认上下文(包含get_object返回的channel对象)
        context = super().get_context_data(**kwargs)
        # 添加自定义上下文内容
        context["example1"] = "I want this on the template"
        context["example2"] = "I want this on the template too"
        return context

关键说明:

  • get_object保持原有逻辑,仅负责获取并返回channel对象,符合类视图的职责划分。
  • get_context_data是Django类视图中添加额外上下文的标准入口:通过super()调用父类方法,能保留原有的上下文数据(比如DetailView自动注入的object变量,对应你的channel对象),再将自定义的键值对添加进去即可。
  • 模板中直接通过{{ example1 }}、{{ example2 }}就能访问你定义的内容,channel对象则可通过{{ object }}或模型小写名{{ channel }}访问。

另外,代码里判断空值建议用channel is None而非channel == None,这是Python的规范写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 05:39:24