Search code examples
djangourl-mapping

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


I have a simple return HttpResponseRedirect(reverse('index')) where 'index' is the name of the view. on running the server the index view is correctly displayed but gives out this error "NoReverseMatch at /vehicle_movement/checkinview"on redirecting.

I was working on django 1.1 for the same project but switched to django 2.2 later. Redirect was working fine with url django 1.1 but gives this error with path django 2.2. Another change that i have done is earlier in 1.1 project the index view url was written in the main url.py but now it is written in the apps urls.py.

This is 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})

This is the Main urls.py

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

This is app urls.py

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

This is the structure

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

The TEMPLATES_DIR

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

Solution

  • You've namespaced your app urls, so you need to use that namespace when reversing them:

    reverse('vehicle_movement:index')
    

    But you've also got two paths with the same name in your app urls, which will cause conflicts, if not an error. Delete one of them.