Django访问帖子详情页出现NoReverseMatch错误求助
错误原因
- profile路由参数传递错误:users应用下的
profile路由定义为接收<int:pk>类型参数,但是detail.html中前两次调用{% url 'profile' %}时传递的是object.user.profile(Profile模型对象),而非该对象的主键值,反向解析时参数类型不匹配触发NoReverseMatch。 - 模板变量拼写错误:模板中存在
objetc.user.profile.picture.url的拼写错误,正确应为object.user.profile.picture.url,拼写错误也会触发异常。 - 评论相关路由缺失/不匹配:模板中使用了
delete-comment、update-comment、add-comment三个路由名称,当前贴出的配置中没有对应命名的路由,若comments应用下未配置对应路由、或者路由参数和模板传递的参数不匹配,也会触发反向解析错误。
修复方案
- 修正profile路由的传参,把模板中所有
{% url 'profile' object.user.profile %}替换为{% url 'profile' object.user.profile.pk %},和评论区的profile传参逻辑保持一致。 - 修正拼写错误,把
objetc改为正确的object。 - 检查comments应用的urls.py,确保配置了对应命名的评论相关路由,且路由参数类型、数量和模板传递的匹配,参考配置如下:
from django.urls import path from .views import DeleteCommentView, UpdateCommentView, AddCommentView urlpatterns = [ path('delete/<int:pk>/', DeleteCommentView.as_view(), name='delete-comment'), path('update/<int:pk>/', UpdateCommentView.as_view(), name='update-comment'), path('add/<int:post_pk>/', AddCommentView.as_view(), name='add-comment'), ]
内容的提问来源于stack exchange,提问作者Ahmed
相关产品推荐
相关产品推荐

