django DRF反向找不到视图名称

dkqlctbz  于 2023-03-20  发布在  Go
关注(0)|答案(1)|浏览(131)

我正在使用djangorest框架API_root,它找不到视图,即使我给它命名。

# board/urls.py
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from .views import BoardList, BoardDetail, api_root

app_name = 'board'
urlpatterns = [
    path('boards/', BoardList.as_view(), name='board-list'), # board-list
    path('boards/<int:pk>', BoardDetail.as_view(), name='board-detail'),
    path('', api_root),
]
urlpatterns = format_suffix_patterns(urlpatterns)
# board/views.py
from django.contrib.auth.models import User
from django.shortcuts import render
from rest_framework import generics, permissions, serializers
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse

from .models import Board
from .serializers import BoardSerializer
from .permissions import IsAuthorOrReadOnly

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

class BoardList(generics.ListCreateAPIView):
    queryset = Board.objects.all()
    serializer_class = BoardSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def perform_create(self, serializer):
        serializer.save(author=self.request.user)

它抛出错误,
找不到'board-list'的反转。'board-list'不是一个有效的视图函数或图案名称。为什么找不到视图名称?

lxkprmvk

lxkprmvk1#

由于您在urls.py中包含了一个app_name,因此您需要使用应用名称指定视图名称,因此:

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

相关问题