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

Django统计帖子点赞时触发'method' object does not support item assignment错误

错误原因与解决方案

错误的核心诱因是你调用父类get_context_data时遗漏了方法调用的括号,导致context变量被赋值为方法对象本身,而非方法执行后返回的上下文字典,自然无法执行字典的键值赋值操作。

修正后的视图代码

class ItemDetailView(DetailView):
    model = Item
    template_name ='waqart/item_detail.html'

    def get_context_data(self, *args, **kwargs):
        # 补全括号和参数,执行父类方法获取上下文字典
        context = super(ItemDetailView, self).get_context_data(*args, **kwargs)
        # DetailView已完成实例查询,无需重复调用get_object_or_404查库
        total_likes = self.object.total_likes()
        context['total_likes'] = total_likes
        return context

额外优化说明

你原代码中额外调用get_object_or_404查询Item实例属于冗余操作,DetailView在执行流程中已经完成了目标对象的查询,直接通过self.object就能拿到当前条目实例,可减少一次不必要的数据库查询。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:06:02