如何在Django 2中注册DRF路由器URL模式 [英] How to register DRF router url patterns in django 2
问题描述
我的DRF路由器指定一个名称空间,以便我可以反向
我的网址:
My DRF routers specify a namespace so that I can reverse
my urls:
网址。 py:
router = DefaultRouter()
router.register('widget/', MyWidgetViewSet, base_name='widgets')
urlpatterns =+ [
url(r'/path/to/API/', include(router.urls, namespace='widget-api'),
]
其中,升级到Django 2时,给出:
Which, when upgrading to django 2, gives:
django.core.exceptions.ImproperlyConfigured:不支持在include()中指定名称空间而不提供app_name。在包含的模块中设置app_name属性,或传递2元组
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 现在需要 app_name
在使用 include 时指定了c $ c> namespace
kwarg code>。由DRF网址路由器构造网址格式时,指定 app_name
的正确方法是什么?我认为文档是有关此主题的Django 2的最新信息。
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.
推荐答案
您需要放入 app_name =应用程序的
。这有点埋藏在文档中: url.py
文件中的'x'
https://docs.djangoproject.com/zh-CN/2.0/topics/http/urls/#id5
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
例如,如果在 /project/project/urls.py
您具有:
path('', include('app.urls', namespace='app'))
然后在相应的url文件中(在 /project/app/urls.py
中),您需要使用以下参数指定 app_name
参数:
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
]
这篇关于如何在Django 2中注册DRF路由器URL模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!