9

I'm trying to set up Django REST Framework with Django 2.0 project which means url(r'^something/' ... has been replaced with path(something/ ....

I'm trying to work out how to set up my rest_framework patterns.

This is what I have:

router = routers.DefaultRouter()
router.register(r'regulations', api.RegulationViewSet)
router.register(r'languages', api.LanguageViewSet)


urlpatterns = [
    ...
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    ...
]

If I go to http://127.0.0.1:8000/regulations I simply get:

Page not found (404)

How should I set up my urlpatterns?

cezar
  • 11,616
  • 6
  • 48
  • 84
HenryM
  • 5,557
  • 7
  • 49
  • 105
  • 1
    `url()` has *not* been replaced. It is still valid. `path()` is an *alternative*. Note, however, you don't seem to have defined a URL for /regulations. – Daniel Roseman Feb 27 '18 at 09:30
  • 1
    @DanielRoseman But he has registered `regulations` with the `router`. He needs to implement it in the `urlpatterns` with `include` or by concatenating: `urlpatterns += router.urls`. – cezar Feb 27 '18 at 10:03

2 Answers2

15
urlpatterns = [
    ...
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    ...
]

with path('', include(router.urls)), you can get:

http://127.0.0.1:8000/regulations/
http://127.0.0.1:8000/languages/

with

path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),

you can get:

http://127.0.0.1:8000/api-auth/{other paths}
Ykh
  • 7,567
  • 1
  • 22
  • 31
  • This will result in `http://localhost:8000/api-auth/regulations`. Also `rest_framework.urls` is right too, but it is for the authentication routes provided by Django REST Framework. The `routers.urls` should be included under another path. – cezar Feb 27 '18 at 10:14
  • Then you should remove the last sentence and add explanation. – cezar Feb 27 '18 at 11:48
3

After registering the router you have to include it in the urlpatterns. The way how @Ykh suggested is technically correct, but with regards to content is missing the point.

urlpatterns = [
    # here you include your router
    path('', include(router.urls)),
    # here you include the authentication paths
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

Now you'll have the following routes:

http://localhost:8000/regulations/
http://localhost:8000/languages/

plus:

http://localhost:8000/api-auth/{other paths}
cezar
  • 11,616
  • 6
  • 48
  • 84