首页 > 解决方案 > 如何定义 APIView 的 url?

问题描述

我正在尝试使用 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)

和路由器:

router = routers.DefaultRouter()
router.register('api/example', views.ExampleView.as_view())

那么,怎么了?谢谢 !

标签: djangodjango-rest-framework

解决方案


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

from django.urls import path

app_name = 'example'

urlpatterns = [
    path('api/example', views.ExampleView.as_view(), name='example')
]

推荐阅读