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

Django表单上传后重定向出现NoReverseMatch错误求助

Django NoReverseMatch 错误解决方法

错误原因

你配置的userprofile URL需要接收user_id参数(路径定义为userprofile/<int:user_id>),但调用redirect('userprofile')时未传递该参数,导致Django无法反向解析出对应的URL路径,从而触发NoReverseMatch错误。而users-profile对应的URL不需要参数,因此重定向正常。

修复步骤

修改views.py中重定向到userprofile的代码,传入正确的user_id参数:

方式一:直接在redirect中传参

# 替换原有的 return redirect('userprofile')
return redirect('userprofile', user_id=request.user.profile.id)

方式二:使用reverse函数传参

return redirect(reverse('userprofile', kwargs={"user_id": request.user.profile.id}))

可选优化

如果myprofile仅用于展示当前登录用户的档案,可以简化视图和URL,无需传递参数:

  1. 修改urls.py:
path('userprofile/', jobs_views.myprofile, name='userprofile')
  1. 修改views.py的myprofile函数:
@login_required
def myprofile(request):
    profile = request.user.profile
    context = {'profile':profile}
    return render(request, 'user/profile.html', context)

之后重定向直接使用return redirect('userprofile')即可,无需传参。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 12:05:31