Li FRANK 2024-08-12 11:38 采纳率: 68.8%
浏览 4
已结题

Django重定向报错NoReverseMatch如何处理?

Django使用redirect重定向报错NoReverseMatch,代码如下

#urls.py
from django.urls import path
from . import views

urlpatterns=[
    path('hello_world/',views.hello_world,name='hello_world'),
    path('a/',views.a,name='a'),
]
#views.py
from django.shortcuts import render
from django.shortcuts import redirect

# Create your views here.
def hello_world(request):
    return render(request,'hello_world.html')

def a(request):
    return redirect('a:hello_world',permanent=True) #使用redirect函数将URL从a/重定向到hello_world/

报错:
NoReverseMatch at /a/
'a' is not a registered namespace

如何处理?谢谢

  • 写回答

1条回答 默认 最新

  • 关注

    上午好☀️☀️☀️️
    本答案参考ChatGPT-3.5

    NoReverseMatch错误表示在尝试访问路径/a/时,目标URL被定义为不存在的视图或方法。

    要解决这个问题,你需要确保您已正确地定义了"/a/"这个视图。例如:

    from django.urls import path
    from . import views
    
    urlpatterns=[
        path('hello_world/', views.hello_world,name='hello_world'),
        path('a/', views.a,name='a'),
    ]
    

    接下来,您可以使用reverse()函数来获取指向"/hello_world/"的链接,并将其设置为目标视图。这可以避免"NoReverseMatch"错误。以下是修复后的代码:

    from django.urls import path
    from . import views
    
    urlpatterns=[
        path('hello_world/', views.hello_world,name='hello_world'),
        path('a/', views.a,name='a'),
    ]
    # views.py
    from django.shortcuts import render
    from django.shortcuts import redirect
    
    # Create your views here.
    def hello_world(request):
        return render(request,'hello_world.html')
    
    def a(request):
        return redirect('/hello_world', permanent=True)
    

    现在,当访问"/a/"时,浏览器会重定向到"/hello_world/",并且该错误已被消除。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 8月12日
  • 已采纳回答 8月12日
  • 创建了问题 8月12日

悬赏问题

  • ¥15 如何在vue.config.js中读取到public文件夹下window.APP_CONFIG.API_BASE_URL的值
  • ¥50 浦育平台scratch图形化编程
  • ¥20 求这个的原理图 只要原理图
  • ¥15 vue2项目中,如何配置环境,可以在打完包之后修改请求的服务器地址
  • ¥20 微信的店铺小程序如何修改背景图
  • ¥15 UE5.1局部变量对蓝图不可见
  • ¥15 一共有五道问题关于整数幂的运算还有房间号码 还有网络密码的解答?(语言-python)
  • ¥20 sentry如何捕获上传Android ndk 崩溃
  • ¥15 在做logistic回归模型限制性立方条图时候,不能出完整图的困难
  • ¥15 G0系列单片机HAL库中景园gc9307液晶驱动芯片无法使用硬件SPI+DMA驱动,如何解决?