Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reverse() raises NoReverseMatch when two apps use the same namespace

Tags:

python

django

I'm trying to use reverse() in a unit test, but it is not able to resolve the url.

tests.py:

from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase

class MyTest(APITestCase):
    def test_cust_lookup(self):
        url = reverse('v1:customer')
        # Other code

The test case fails in the first line of the test with the following error:

NoReverseMatch: Reverse for 'customer' with arguments '()' and keyword arguments '{}'  not found. 0 pattern(s) tried: []

Does "0 patterns tried" means the test is not even able to find the root urls.py? Or is there something else that I misconfigured?

proj/settings.py:

ROOT_URLCONF = 'proj.urls'

proj/myapp/urls.py:

from django.conf.urls import url
import views

urlpatterns = [
    url(r'cust/$', views.CustomerView.as_view(), name='customer')
]

proj/urls.py:

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^api1/v1/', include('myapp1.urls', namespace='v1')),
    url(r'^api2/v1/', include('myapp2.urls', namespace='v1'))
]
like image 942
Rohit Jain Avatar asked Oct 20 '22 07:10

Rohit Jain


1 Answers

Don't have different apps under same url namespace, Django isn't able to deal with it and doesn't tell you that that's the issue. Change the namespaces to be unique for each app.

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^api1/v1/', include('myapp1.urls', namespace='app1-v1')),
    url(r'^api2/v1/', include('myapp2.urls', namespace='app2-v1'))
]

Reverse the url with reverse('app1-v1:customer').

like image 151
Rohit Jain Avatar answered Oct 22 '22 00:10

Rohit Jain