0

I have a very simple Django Rest Framework application, my urls.py looks like the following

router = routers.DefaultRouter()
router.register(r'activity-list', activities.views.ArticleViewSet)

urlpatterns = [

    url(r'^admin/', admin.site.urls),

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

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

# Base/default URL, when all else fails
urlpatterns += [
    url(r'', TemplateView.as_view(template_name='index.html')),
]

When I run the url http://127.0.0.1:8000/api/activity-list, the route that comes from the DRF router never gets reached. The server always seems to give precedence to the default URL, and index.html is always rendered.

However, if I change the Default URL to:

# Base/default URL, when all else fails
urlpatterns += [
    url(r'BLABLABLA', TemplateView.as_view(template_name='index.html')),
]

Only then are the DRF routes reachable. This is what makes me think it's a precedence issue. The DRF routes are working, they just always get beaten by the default URL.

I've tried variants suggested in the DRF docs, without luck, such as :

Moreover, /admin works fine, which is why I suspect that it has to do with the DRF router in particular.

But the same thing keeps happening. How can I make my DRF routes reachable while maintaining a default route for the server to land on?

Update: So I've found that adding a trailing slash to the api URL causes it to work. This has led me to these two (1 and 2) questions.

Community
  • 1
  • 1
Jad S
  • 2,705
  • 6
  • 29
  • 49

2 Answers2

3

Finally figured it out. According to the DRF docs:

By default the URLs created by SimpleRouter are appended with a trailing slash. This behavior can be modified by setting the trailing_slash argument to False when instantiating the router. For example:

router = SimpleRouter( trailing_slash = False )

Having set this as the setting of the router and transformed my route to r'activity-list', it now works with or without the trailing slash.

Jad S
  • 2,705
  • 6
  • 29
  • 49
0

You will have to learn url dispatcher in django. Your default url's and DRF route's url's pattern is same, and default url is on top of the urlpatterns thus that url is getting triggered.

How Django processes a request

Kishor Pawar
  • 3,386
  • 3
  • 28
  • 61