我在尝试弄清楚如何为我的 Django 博客实现点赞系统时遇到了问题。我有一个帖子详细信息视图和一个PostRedirectView。我希望重定向视图获取我查看的帖子的绝对 URL,并切换喜欢/不喜欢,因为我的喜欢系统是链接在我的 models.py 中的帖子的 ManyToManyField。这是相关代码:views.pyclass PostDetailView(DetailView): model = Post template_name = 'blog/post_detail.html' context_object_name = 'post' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) comments_connected = Comment.objects.filter(post_connected=self.get_object()).order_by('-date_posted') data['comments'] = comments_connected data['form'] = NewCommentForm(instance=self.request.user) return data def post(self, request, *args, **kwargs): new_comment = Comment(content=request.POST.get('content'), author=self.request.user, post_connected=self.get_object()) new_comment.save() return self.get(self, request, *args, **kwargs)class PostLikeRedirect(RedirectView): def get_redirect_url(self, *args, **kwargs): obj = get_object_or_404(Post, pk=self.kwargs.get('id')) return obj.get_absolute_url()urls.py path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/<int:pk>/like', PostLikeRedirect.as_view(), name='post-like'),models.pyclass Post(models.Model): content = models.TextField(max_length=1000) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="users_who_authored") like = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="users_who_liked") def __str__(self): return f'{self.author} posts: {self.content[:8]}' @property def number_of_comments(self): return Comment.objects.filter(post_connected=self).count() def __str__(self): return f'{self.author} posted'当我转到 post/id(eg 2)/like 时收到的错误是 404 page not found 和错误消息No Post matches the given query.我知道该错误意味着什么,我只是无法查明确切的时间以及我没有正确传递查询的位置
1 回答
芜湖不芜
TA贡献1796条经验 获得超7个赞
id您正在尝试从 URL获取,但它被定义为pk。所以,改变你的观点
class PostLikeRedirect(RedirectView):
def get_redirect_url(self, *args, **kwargs):
obj = get_object_or_404(Post, pk=self.kwargs["pk"])
^^^^^^^^^^^^^^^^^^^^^
return obj.get_absolute_url()
添加回答
举报
0/150
提交
取消