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,无需传递参数:
- 修改urls.py:
path('userprofile/', jobs_views.myprofile, name='userprofile')
- 修改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
相关产品推荐
相关产品推荐

