Django中带include的路由名称无法reverse,如何实现指定跳转?
问题描述
我设置了如下Django路由:
Django项目:core/urls.py
def redirect_index(request): return redirect(reverse('account'), permanent=False) urlpatterns = [ path('', redirect_index, name='index'), path('account/', include('identity.urls'), name='account'), ]
Django应用:identity/urls.py
app_name = 'identity' def redirect_index(request): return redirect(reverse('identity:login'), permanent=False) def view_login(request): context = {"test_context": 'This is a test context'} return render(request, "common/base.html", context) urlpatterns = [ path('', redirect_index, name='index'), path('login', view_login, name='login'), ]
当访问http://localhost:8000/时,出现错误:
NoReverseMatch at /
Reverse for 'account' not found. 'account' is not a valid view function or pattern name.
我希望实现:用户访问根路径/时,先重定向到/account/,再从该路径重定向到/account/login,且保留两次独立的重定向。目前使用reverse('identity:index')或reverse('identity:login')可正常工作,请问能否按原需求实现?
解决方案
可以实现你的需求,原代码报错是因为reverse('account')无法解析,include引入路由时设置的name='account'不是可直接反向解析的视图名,而是路由分组的命名空间前缀。下面两种方法都能实现两次独立重定向:
方法一:硬编码路径重定向
直接在根路由的重定向函数里写目标路径字符串,跳过反向解析:
# core/urls.py def redirect_index(request): return redirect('/account/', permanent=False)
访问/时会直接跳转到/account/,触发identity应用内的重定向逻辑,最终跳转到/account/login,完成两次独立跳转。
方法二:反向解析到identity的index路由
利用你已经验证可行的reverse('identity:index')来实现根路径跳转,这更符合Django的最佳实践,避免硬编码路径带来的维护问题:
# core/urls.py def redirect_index(request): return redirect(reverse('identity:index'), permanent=False)
这种方式同样会先跳转到/account/,再触发二次重定向到/account/login,完全满足你的需求。
内容的提问来源于stack exchange,提问作者fishfin
相关产品推荐
相关产品推荐

