Django REST框架 - 使用reverse()时的NoReverseMatch

时间:2016-04-25 14:49:10

标签: python django django-rest-framework

我一直试图使用reverse()函数返回一些URL,但无论如何,我得到NoReverseMatch异常:

Reverse for 'folder' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

为了排除故障,我创建了一些愚蠢的代码,但它仍然无法工作。以下是我的观点:

from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework.views import APIView

class Folder(APIView):
    def get(self, request, format=None):
        return Response({'url': reverse('folder', request=request)})

这是我的网址格式:

from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from music import views

urlpatterns = format_suffix_patterns([
    url(r'^folder/$', views.Folder.as_view(), name='folder')])

2 个答案:

答案 0 :(得分:4)

你不应该通过请求:

{'url': reverse('folder')}

{'url': reverse('appname:folder')}

如果您使用namespaced URLs

答案 1 :(得分:0)

当尝试在serializers.py中获取模型的反向时,我遇到了与reverse()Django-Rest-Framework相同的问题

    ....

    def get_links(self, obj):
        request = self.context['request']
        return {
            'self': reverse('sprint-detail',
                kwargs={'pk': obj.pk}, request=request),
        }

将应用反向添加可解决my_app

    ....

    def get_links(self, obj):
        request = self.context['request']
        return {
            'self': reverse('my_app:sprint-detail',
                kwargs={'pk': obj.pk}, request=request),
        }