Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register DRF router url patterns in django 2

My DRF routers specify 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'),
]

Which, 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 patterns and app_name instead.

Django 2 now requires app_name if the namespace kwarg is specified when using include. What's the right way to specify app_name when the url patterns are constructed by a DRF url router? I don't think the documentation is up-to-date for django 2 on this subject.

like image 474
Escher Avatar asked Dec 05 '17 13:12

Escher


1 Answers

You need to put app_name = 'x' in your application's url.py file. This is a little buried in the 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
] 
like image 160
eric Avatar answered Nov 14 '22 16:11

eric