首页 > 解决方案 > Like button Django3 - KeyError at /nutriscore/exemple-1/ 'pk'

问题描述

我希望你很好。我是 Python 的初学者,我正在尝试在这样的博客文章中实现一个类似的按钮。在管理部分,我可以看到谁在点击类似的东西。

但是我遇到两个问题:

模型.py:

class Post(models.Model):
    ...
    likes = models.ManyToManyField(User, related_name='nutriscore_posts')
    
    def total_likes(self):
        return self.likes.count()

视图.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 context

网址.py

path('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>

非常感谢 :)

标签: pythondjango

解决方案


第一个问题:你将 pk 传递给重定向,它是一个整数(根据你的 urls.py)到 url: args=[str(pk)]。如果你想重定向到一个url,/nutriscore/exemple-1你应该传递slug而不是pk(我猜这是id)并相应地调整你的urls.py。

第二个问题:你确定那个帖子有一个叫做pk的属性/键吗?这不应该是身份证吗?喜欢:

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

推荐阅读