You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django评论更新功能触发404错误,请求排查原因

Django评论更新功能404错误排查与解决

实现评论更新功能时出现Page not found (404)错误,提示“No comments found matching the query”。相关代码如下:

views.py

class CommentCreateView(LoginRequiredMixin, CreateView):
    model = Comments
    fields = ['content']
    template_name = 'blog/comment_create.html'

    def form_valid(self, form):
        form.instance.post_id = self.kwargs['pk']
        form.instance.author = self.request.user
        messages.success(self.request, 'You have made a comment')
        return super().form_valid(form)

class CommentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Comments
    fields = ['content']
    template_name = 'blog/comment_update.html'

    def test_func(self):
        comment = self.get_object()
        if self.request.user == comment.author:
            return True
        else:
            return False

    def form_valid(self, form):
        messages.success(self.request, 'You have updated the post')
        return super().form_valid(form)

urls.py

from django.contrib import admin
from django.urls import path
from blog.views import home, about, PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, CommentCreateView, CommentUpdateView

urlpatterns = [
    # path('', home, name='blog_home'),
    path('', PostListView.as_view(), name='blog_home'),
    path('post/<int:pk>', PostDetailView.as_view(), name='post_detail'),
    path('post/<int:pk>/update', PostUpdateView.as_view(), name='post_update'),
    path('post/<int:pk>/delete', PostDeleteView.as_view(), name='post_delete'),
    path('post/create/', PostCreateView.as_view(), name='post_create'),
    path('post/<int:pk>/create_comment/', CommentCreateView.as_view(), name='comment_create'),
    path('post/<int:pk>/update_comment/<int:comment_id>', CommentUpdateView.as_view(), name='comment_update'),

    path('about/', about, name='blog_about'),
]

models.py

class Comments(models.Model):
    content = models.CharField(max_length=100)
    date_posted = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(to=User, on_delete=models.CASCADE)
    post = models.ForeignKey(to=Post, related_name='comments',on_delete=models.CASCADE)

    def __str__(self):
        return f'Comment by {self.author} for {self.post.title}'

    def get_absolute_url(self):
        return reverse('post_detail', kwargs={'pk': self.post.pk})

帖子模板代码

{% for comment in post.comments.all %}
    <article class="media content-section">
    <div class="small text-muted">Comment by {{ comment.author }}</div>
            <a href="{% url 'comment_update' pk=object.pk comment_id=comment.pk %}">{{ comment.content }}</a>
        <div class="small text-muted"> Posted on {{ comment.date_posted }}</div>
    </article>

{% endfor %}

错误原因

Django的UpdateView默认使用URL中的pk参数查找对应模型对象,但你的评论更新URL使用的是comment_id参数,视图无法通过默认逻辑匹配到评论实例,因此抛出404错误。

解决办法

提供两种可行修改方案:

方案一:统一URL参数名

  1. 修改urls.py中的评论更新路径,将帖子参数重命名避免冲突,评论参数改为默认的pk:
path('post/<int:post_pk>/update_comment/<int:pk>', CommentUpdateView.as_view(), name='comment_update'),
  1. 同步修改模板中的URL调用参数:
<a href="{% url 'comment_update' post_pk=object.pk pk=comment.pk %}">{{ comment.content }}</a>
  1. 若视图中需要获取帖子ID,可通过self.kwargs['post_pk']调用。

方案二:重写视图的对象获取方法

保持现有URL和模板不变,在CommentUpdateView中手动指定查询参数:

class CommentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Comments
    fields = ['content']
    template_name = 'blog/comment_update.html'

    def get_object(self, queryset=None):
        return Comments.objects.get(pk=self.kwargs['comment_id'])

    def test_func(self):
        comment = self.get_object()
        return self.request.user == comment.author

    def form_valid(self, form):
        messages.success(self.request, 'You have updated the comment')
        return super().form_valid(form)

额外提示

  • 建议将form_valid中的提示信息从"You have updated the post"改为"You have updated the comment",表述更准确。
  • 测试时确保登录用户是评论的作者,否则test_func会拒绝访问(此为权限控制,非当前404错误原因)。

内容的提问来源于stack exchange,提问作者Кирилл Черняк

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 22:58:22