使用UpdateView提交时出现NoReverseMatch错误,求解决
解决Django UpdateView提交后NoReverseMatch错误
问题根源
你的URL配置中设置了app_name = 'HealthHub',所有视图名称必须带上命名空间前缀才能完成反向解析。但模型的get_absolute_url方法里直接使用reverse('health_hub_history'),未指定命名空间,导致Django无法识别对应的视图路径。
修复方案
方案一:修正模型的get_absolute_url方法
修改models.py中的get_absolute_url,添加命名空间前缀:
def get_absolute_url(self): return reverse('HealthHub:health_hub_history')
方案二:在UpdateView中直接指定success_url
如果不想依赖模型的get_absolute_url,可以在EditHealth视图里显式设置跳转路径:
from django.urls import reverse_lazy class EditHealth(UpdateView): model = HealthStats template_name = 'health_hub_edit.html' fields = ['weight', 'run_distance', 'run_time'] success_url = reverse_lazy('HealthHub:health_hub_history')
注意事项
- 确认
urls.py中health_hub_history的名称拼写无误 - 命名空间
HealthHub必须和app_name的大小写完全匹配(Django对命名空间大小写敏感)
内容的提问来源于stack exchange,提问作者BenD2525
相关产品推荐
相关产品推荐

