How to register DRF router url patterns in django 2

My DRF routers define a namespace so that I can reverse my URLs:

urls.py:

 router = DefaultRouter() router.register('widget/', MyWidgetViewSet, base_name='widgets') urlpatterns =+ [ url(r'/path/to/API/', include(router.urls, namespace='widget-api'), ] 

What when upgrading to django 2 gives:

django.core.exceptions.ImproperlyConfigured: specifying a namespace in include () without providing an app_name is not supported. Set the app_name attribute in the included module or pass a 2-tuple containing the list of templates and username.

Django 2 now requires app_name if namespace kwarg is specified when using include . What is the correct way to specify app_name when url patterns are created by the DRF url router? I do not think the documentation is relevant for django 2 on this.

+5
source share
2 answers

You need to put app_name = 'x' in the url.py application url.py . This is a bit like documentation:
https://docs.djangoproject.com/en/2.0/topics/http/urls/#id5

For example, if in /project/project/urls.py you have:

 path('', include('app.urls', namespace='app')) 

Then in the corresponding url file (in /project/app/urls.py ) you need to specify the app_name parameter with:

 app_name = 'app' #the weird code urlpatterns = [ path('', views.index, name = 'index'), #this can be anything ] 
+9
source

You need to include router.urls as a tuple and add the application name to the tuple, instead of including only router.urls

According to your example, you should try something like:

 router = DefaultRouter() router.register('widget/', MyWidgetViewSet, base_name='widgets') urlpatterns =+ [ url(r'/path/to/API/', include((router.urls, 'my_app_name'), namespace='widget-api'), ] 
0
source

Source: https://habr.com/ru/post/1273858/


All Articles