Jad S Jad S - 2 months ago 11
Python Question

Django DRF: Default URL always gets trigered first instead of route.url

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.

Answer

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.