Home > Software design >  django - 'module' object does not support item assignment
django - 'module' object does not support item assignment

Time:04-23

When clicking the like button on a article the following error shows up:

'module' object does not support item assignment

and it leads to this piece of code:

    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

but when I remove this piece the feature works fine but you cant see the likes - the only way you know its working is if you go into django admin and see which user is highlighted.

my articles 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)]))

my articles 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)])

full error pic:

error picture

CodePudding user response:

You have imported the context module which is not correct for this particular scenario.

PFB modified code which is working for me.

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
  • Related