我希望你很好。我是 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 context
urls.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>
多谢 :)
慕盖茨4494581
至尊宝的传说
相关分类