如何定义 APIView 的 url?

Pyt*_*gus 5 django django-rest-framework

我正在尝试使用 Django Rest Framework 制作 APIView。当我将视图与 url 相关联时,出现此错误:

AssertionError: basename argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute.

这是我的 APIView :

class ExampleView(APIView):
    authentication_classes = (SessionAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated,)

    def get(self, request, format=None):
        content = {
            'user': unicode(request.user),  # `django.contrib.auth.User` instance.
            'auth': unicode(request.auth),  # None
        }
        return Response(content)
Run Code Online (Sandbox Code Playgroud)

和路由器:

router = routers.DefaultRouter()
router.register('api/example', views.ExampleView.as_view())
Run Code Online (Sandbox Code Playgroud)

那么,怎么了?谢谢 !

Ken*_*ars 7

您只需要将路径添加到您的urlpatterns. 路由器与视图集一起使用。

from django.urls import path

app_name = 'example'

urlpatterns = [
    path('api/example', views.ExampleView.as_view(), name='example')
]
Run Code Online (Sandbox Code Playgroud)