2

I'm working on this Django project for learning and I'm not able to resolve the URL using reverse().

I have tried to understand this concept from online documentations and I'm not able to succeed with it.

I'm using ModelViewSet in my views.py

In my tests.py

POSTS_URL = reverse('posts:posts-list')

And this is my urls.py of posts(i.e., app)

app_name = 'posts'


router = DefaultRouter()
router.register('', PostsViewSet)


urlpatterns = [
path('', include(router.urls))
]

This is my urls.py in root

urlpatterns = [
path('admin/', admin.site.urls),
path('api/posts/', include('posts.urls')),
path('docs/', include_docs_urls(title='My API title')),
]

And this is the error I'm getting

django.urls.exceptions.NoReverseMatch: Reverse for 'posts-list' not found. 'posts-list' is not a valid view function or patternname.

And also can someone suggest a good place to understand properly how reverse() and routers work together..

Prashanth S.
  • 410
  • 4
  • 19

1 Answers1

1

In your urls.py app_name doesn't seem to get used and the router uses the model's name (singular) per default, therefore reverse("post-list") should work.

If you want to namespace your urls you should rather do something like path('api/posts/', include('posts.urls', 'posts')) then reverse('posts:post-list') should work.

Bernhard Vallant
  • 49,468
  • 20
  • 120
  • 148