Django 2.0和DRF 3.7.7路由器

时间:2017-12-30 20:49:30

标签: python django django-rest-framework url-routing

我使用Django 2.0和DRF 3.7.7(两者都是新手)并尝试在app_config / urls.py中添加网址模式:

router = routers.DefaultRouter()
router.register(r'^submit_free_account', SubmitFreeAccount, 'SubmitFreeAccount')

app_name = 'app_config'  #the weird code

urlpatterns = [
    path('getSourcesNodes', GetSourcesNodes.post, name='GetSourcesNodes'),
    path('getAppsNodes', GetAppsNodes.post, name='GetAppsNodes'),
]

urlpatterns += router.urls

在主urls.py中:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('config/', include('app_config.urls', namespace='app_config')),
]

因此,当我尝试请求config / submit_free_account时,我发现了由Django尝试的奇怪URL模式的404错误:

config/ ^$ [name='api-root']
config/ ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root']

如何在Django 2.0中正确添加路由器URL模式?

2 个答案:

答案 0 :(得分:0)

请参阅:Django REST Framework URLs with Django 2.0

router = routers.DefaultRouter()
# change to (see user8814926's answer):
router.register('submit_free_account', SubmitFreeAccount, 'SubmitFreeAccount')

app_name = 'app_config'  #the weird code

urlpatterns = [
    path('getSourcesNodes', GetSourcesNodes.post, name='GetSourcesNodes'),
    path('getAppsNodes', GetAppsNodes.post, name='GetAppsNodes'),

    #add this:
    path('', include(router.urls)),
]

所以总结一下:

  • 不要使用正则表达式
  • 不是通过添加到列表来添加路由,而是使用上面显示的include方法

答案 1 :(得分:-2)

更改

router.register(r'^submit_free_account', SubmitFreeAccount, 'SubmitFreeAccount')

router.register('submit_free_account', SubmitFreeAccount, 'SubmitFreeAccount')