django - 'module' 对象不支持项目分配

django - 'module' object does not support item assignment

点击文章上的赞按钮时出现以下错误:

'module' object does not support item assignment

它导致这段代码:

    def get_context_data(self, *args,**kwargs):
        stuff = get_object_or_404(Article, id=self.kwargs['pk']) #grab article with pk that you're currently on
        total_likes = stuff.total_likes()
        context["total_likes"] = total_likes
        return context

但是当我删除这个部分时,该功能工作正常但你看不到喜欢的东西 - 你知道它工作的唯一方法是如果你进入 django 管理并查看哪个用户被突出显示。

我的文章views.py:

class ArticleDetailView(LoginRequiredMixin,DetailView):
    model = Article
    template_name = 'article_detail.html'

    def get_context_data(self, *args,**kwargs):
        stuff = get_object_or_404(Article, id=self.kwargs['pk']) #grab article with pk that you're currently on
        total_likes = stuff.total_likes()
        context["total_likes"] = total_likes
        return context
def LikeView(request, pk):
    article = get_object_or_404(Article, id=request.POST.get('article_id')) 
    article.likes.add(request.user) #might need check later
    return HttpResponseRedirect(reverse('article_detail', args=[str(pk)]))

我的文章models.py:

class Article(models.Model):
    title = models.CharField(max_length=255)
    body = RichTextField(blank=True, null=True)
    #body = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    likes = models.ManyToManyField(get_user_model(), related_name='article_post')
    author = models.ForeignKey(
        get_user_model(),
        on_delete=models.CASCADE,
    )
    
    def total_likes(self): 
        return self.likes.count()
    
    def __str__(self):
        return self.title
    
    def get_absolute_url(self):
        return reverse('article_detail', args=[str(self.id)])

完整错误图片:

您导入的上下文模块不适合此特定场景。

PFB 修改后的代码对我有用。

class ArticleDetailView(LoginRequiredMixin, DetailView):
    model = Article
    template_name = "article_detail.html"

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(**kwargs)
        # grab article with pk that you're currently on
        stuff = get_object_or_404(Article, id=self.kwargs["pk"])
        total_likes = stuff.total_likes()
        context["total_likes"] = total_likes
        return context