Django Rest框架 - NoReverseMatch

时间:2017-11-20 15:03:46

标签: django django-rest-framework

我正在使用Django 1.11.7和DjangoRestFramework 3.7.3

我有一个应用程序饭菜

餐/ urls.py

app_name = 'meals'

urlpatterns = format_suffix_patterns([
    url(r'^$', views.api_root),
    url(r'^food/$', views.FoodList.as_view(), name='food-list'),
    url(r'^food/(?P<pk>[0-9]+)/$', views.FoodDetail.as_view(), name='food-detail'),
])

餐/ views.py

@api_view(['GET'])
def api_root(request, format=None):
    return Response({
        'Foods': reverse('food-list', request=request, format=format),
    })

当我跑步时,我收到错误NoReverseMatch。

但是如果我在urls.py中删除了app_name = 'meals',那就可以了

# app_name = 'meals'

    urlpatterns = format_suffix_patterns([
        url(r'^$', views.api_root),
        url(r'^food/$', views.FoodList.as_view(), name='food-list'),
        url(r'^food/(?P<pk>[0-9]+)/$', views.FoodDetail.as_view(), name='food-detail'),
    ])

如何在保留app_name的同时使其正常工作?

2 个答案:

答案 0 :(得分:2)

如果您使用app_name = 'meals',则必须在撤消网址时包含应用名称:

reverse('meals:food-list', request=request, format=format),

答案 1 :(得分:0)

您可以从apps.py文件中调用它