找不到 'index' 的反向。 'index' 不是有效的视图函数或模式名称

Reverse for 'index' not found. 'index' is not a valid view function or pattern name

我有一个简单的 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')

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