亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

喜歡按鈕 Django3 - KeyError at /nutriscore/exemple-1/

喜歡按鈕 Django3 - KeyError at /nutriscore/exemple-1/

HUH函數 2023-03-22 16:54:50
我希望你很好。我是 Python 的初學者,我正在嘗試在這樣的博客文章中實現一個贊按鈕。在管理部分,我可以看到誰在點擊類似的內容。但是我遇到兩個問題:第一個:當我點擊“贊”按鈕時,“返回”使用這種 url nutriscore/4/ 重定向我,或者我的文章使用了一個 slug(比如 /nutriscore/exemple-1/。你有什么想法嗎?第二個:當我想顯示喜歡的數量時 {{ total_likes }} 我有這個問題:KeyError at /nutriscore/exemple-1/ 'pk'Models.py:class Post(models.Model):    ...    likes = models.ManyToManyField(User, related_name='nutriscore_posts')        def total_likes(self):        return self.likes.count()Views.py:class PostList(generic.ListView):    queryset = Post.objects.filter(status=1).order_by('-created_on')    template_name = 'index.html'def LikeView(request, pk):    post = get_object_or_404(Post, id=request.POST.get('post_id'))    post.likes.add(request.user)    return HttpResponseRedirect(reverse('post_detail', args=[str(pk)]))class PostDetail(generic.DetailView):    model = Post    context_object_name = 'post'    template_name = 'post_detail.html'        def get_context_data(self, **kwargs):        context = super(PostDetail, self).get_context_data(**kwargs)        stuff = get_object_or_404(Post, id=self.kwargs['pk'])        total_likes = stuff.total_likes        context['total_likes'] = total_likes        return contexturls.pypath('like/<int:pk>', LikeView, name="like_post"),post_detail.html    <form action="{% url 'like_post' post.pk %}" method="POST">{% csrf_token %}<button type="submit" name="post_id" value="{{ post.id }}" class="cherry-likes"><img src="static/img/like.png" width="30px" height="30px" class="" title=""></button></form>多謝 :)
查看完整描述

2 回答

?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

您pk應該是int。您還在您的網址中指定為 int,但在視圖中沒有指定。


post = get_object_or_404(Post, id=pk )

if request.method == "POST": 

     post.likes.add(request.user)

     return redirect('post_detail', post.pk)

要顯示帖子的總贊數,您需要添加property這樣的裝飾器


@property

def total_likes(self):

    return self.likes.count()

現在在詳細信息模板{{post.total_likes}}中將顯示結果。


無需編寫get_context_data方法來顯示 total_likes。


查看完整回答
反對 回復 2023-03-22
?
至尊寶的傳說

TA貢獻1789條經驗 獲得超10個贊

第一個問題:你將 pk 傳遞給重定向,它是一個整數(根據你的 urls.py)到 url: args=[str(pk)]。如果你想重定向到一個 url,/nutriscore/exemple-1你應該傳遞 slug 而不是 pk(我猜這是 id)并相應地調整你的 urls.py。

第二個問題:你確定那個帖子有一個名為 pk 的屬性/鍵嗎?這不應該是id嗎?喜歡:

<form action="{% url 'like_post' post.id %}" method="POST">{% csrf_token %}<button type="submit" name="post_id" value="{{ post.id }}" class="cherry-likes"><img src="static/img/like.png" width="30px" height="30px" class="" title=""></button></form>



查看完整回答
反對 回復 2023-03-22
  • 2 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號