Django中/detail/3/页面出现NoReverseMatch错误求助
解决Django待办应用的NoReverseMatch错误
错误现象
访问待办列表详情页(http://127.0.0.1:8000/detail/3/)时触发NoReverseMatch错误,提示无法找到completed_list_item的反向匹配,传入的参数为空字符串,匹配规则为['completed\-item/(?P<list_pk>[0-9]+)/(?P<item_pk>[0-9]+)/\Z']。
错误回溯:
Environment: Request Method: GET Request URL: http://127.0.0.1:8000/detail/3/ Django Version: 4.1.4 Python Version: 3.10.7 Exception Type: NoReverseMatch at /detail/3/ Exception Value: Reverse for 'completed_list_item' with arguments '('', '')' not found. 1 pattern(s) tried: ['completed\-item/(?P<list_pk>[0-9]+)/(?P<item_pk>[0-9]+)/\Z']
问题定位
核心问题出在模板URL反向解析的参数名称错误:
TodoList模型默认主键字段是pk,但模板中误用了不存在的todo_list.list_pk,导致传入空值ListItem模型默认主键字段是pk,模板中误用了不存在的item.item_pk,同样传入空值
另外,视图中list_items的过滤逻辑可以简化(非必须,但更规范):借助外键关联,直接用todo_list.list_items.all()即可获取当前列表的所有子项,无需额外过滤item_list = todo_list.pk。
修复方案
1. 修正模板中的URL反向解析代码
修改detail.html里的表单标签:
<form method="POST" action="{% url 'completed_list_item' todo_list.pk item.pk %}">
2. 优化视图子项查询(可选)
将views.py中detail视图的子项查询代码:
list_items = todo_list.list_items.filter(item_list = todo_list.pk)
改为:
list_items = todo_list.list_items.all()
3. 确认URL配置(当前已正确,无需修改)
urls.py的路径配置符合要求,确保completed_list_item的路径参数list_pk、item_pk与视图函数参数名一致:
path('detail/<int:pk>/', views.detail, name='detail'), path('completed-item/<int:list_pk>/<int:item_pk>/', views.completed_list_item, name='completed_list_item'),
验证修复
重启Django服务后,访问详情页,表单的action属性会正确生成为类似/completed-item/3/1/的路径,不再触发NoReverseMatch错误。
内容的提问来源于stack exchange,提问作者Lorenzo
相关产品推荐
相关产品推荐

