Django rest Framework: NoReverseMatch error even when pattern name has been defined

Viewed 1985

I've created a api_root in my views.py

@api_view(['GET'])
def api_root(request, format=None):
  return Response({
      'books': reverse('api_book_list'),
      'users': reverse('api_user_list')
})

Which is referred to by my rest_api.urls.py

urlpatterns = [
url(r'', api_root),
url(r'^books/$', BookList.as_view(), name='api_book_list'),
url(r'^books/(?P<pk>[0-9]+)/$', BookDetail.as_view(), name='book-detail'),


url(r'^users/$', UserList.as_view(), name='api_user_list'),
url(r'^users/(?P<pk>[0-9]+)/$', UserDetail.as_view(), name='user-detail'),
]

My project root urls.py links to the rest_api.urls.py with the following url-config:

url(r'^api/v1/', include('rest_api.urls', namespace='api')),

Yet, when I visit the /api/v1/ page I get the following error:

NoReverseMatch at /api/v1/
Reverse for 'api_book_list' not found. 'api_book_list' is not a valid view 
function or pattern name.

But I've defined the pattern name in my urls.py, does anyone have a idea why Django still wont recognize it?

1 Answers

You have defined namespace='api' to root url so you need append api before url name while reversing

reverse('api:api_book_list')
reverse('api:api_user_list')

Read official docs: Reversing namespace urls

Related