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

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条回答 默认 最新

  • 檀越@新空间 2024-08-12 11:40
    关注

    上午好☀️☀️☀️️
    本答案参考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日