【问题标题】:Reverse for 'index' not found. 'index' is not a valid view function or pattern name未找到“索引”的反向。 “索引”不是有效的视图函数或模式名称
【发布时间】:2019-12-30 21:27:30
【问题描述】:

我有一个简单的 return HttpResponseRedirect(reverse('index')) ,其中 'index' 是视图的名称。在运行服务器时,索引视图会正确显示,但在重定向时会出现此错误“NoReverseMatch at /vehicle_movement/checkinview”。

我正在为同一个项目使用 django 1.1,但后来切换到 django 2.2。重定向在 url django 1.1 上运行良好,但在路径 django 2.2 中出现此错误。我所做的另一个更改是在 1.1 项目的早期,索引视图 url 写在主 url.py 中,但现在它写在应用程序 urls.py 中。

这是views.py

def index(request):
    return render(request,'vehicle_movement/index.html',{})

def CheckinView(request):
    if request.method == "POST":
        checkin_form = CheckinForm(data = request.POST)
        if checkin_form.is_valid():
            checkin_form.save()
            return HttpResponseRedirect(reverse('index'))
        else:
            HttpResponse("Error")
    else:
        checkin_form = CheckinForm()
    return render(request,'vehicle_movement/checkin.html',{'checkin_form':checkin_form})

这是主要的 urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include(('vehicle_movement.urls','vehicle_movement'),namespace = 'vehicle_movement')),
]

这是应用程序 urls.py

app_name = 'vehicle_movement'
urlpatterns = [
    path('', views.index, name='index'),
    path('index', views.index, name='index'),
]

这是结构

Warehouse
  -Warehouse
    -init.py
    -settings.py
    -urls.py
  -static
  -templates
  -vehicle_movement
    -urls.py
    -views.py

TEMPLATES_DIR

TEMPLATES_DIR = os.path.join(BASE_DIR,'templates')
``

【问题讨论】:

  • 您的应用程序 url 是命名空间的。你应该reverse('vehicle_movement:index')
  • 你也不应该在同一个命名空间中有两个名为“index”的路径。

标签: django url-mapping


【解决方案1】:

您已经为您的应用程序 URL 命名了命名空间,因此在反转它们时需要使用该命名空间:

reverse('vehicle_movement:index')

但是您的应用程序 url 中也有两个同名的路径,如果不是错误的话,这会导致冲突。删除其中一个。

【讨论】:

  • 这行得通。我只是想尽一切办法让它工作,所以添加了两个索引路径现在将删除一个。
猜你喜欢
  • 2020-10-15
  • 1970-01-01
  • 2023-02-06
  • 2021-08-07
  • 2018-11-19
  • 2019-04-06
  • 2019-08-13
  • 2019-11-04
  • 1970-01-01
相关资源
最近更新 更多