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

Django UpdateView实现BuildLog更新功能触发Page not found错误求解

错误原因

Django 内置UpdateView默认会读取URL中名为pk的参数作为查询目标数据的主键,你的路由中BuildLog对应的主键参数名为pkz,视图无法识别,找不到对应数据就会抛出404。同时你的视图中写的template属性是错误写法,正确属性名为template_name,这个问题后续也会导致模板加载错误。


解决方案

方案1:调整路由参数命名(改动最小)

直接修改路由中参数命名,将父级Post的参数改为post_pk,BuildLog的主键参数改为pk,无需修改视图即可正常运行:

path('post/<int:post_pk>/build-log/<int:pk>/update/', UpdateBuildLog.as_view(), name='build-log-update')

方案2:不改动路由,修改视图配置

如果要保留原来的pk和pkz参数命名,给视图增加pk_url_kwarg配置指定主键参数名即可,同时修正template属性名:

class UpdateBuildLog(UpdateView):
    model = BuildLog
    form_class = BuildLogupdateForm
    template_name = 'blog/buildlog_update.html'
    pk_url_kwarg = 'pkz' # 告诉视图用URL中的pkz参数作为查询主键

如果需要额外校验该BuildLog是否属于URL中对应的父Post,避免用户通过修改URL非法访问其他Post下的日志,可以重写get_queryset方法做过滤:

class UpdateBuildLog(UpdateView):
    model = BuildLog
    form_class = BuildLogupdateForm
    template_name = 'blog/buildlog_update.html'
    pk_url_kwarg = 'pkz'

    def get_queryset(self):
        # 仅查询属于当前父Post的BuildLog
        return super().get_queryset().filter(post_id=self.kwargs['pk'])

内容的提问来源于stack exchange,提问作者Wazy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:15:02