django 无法使用视图名称“user-detail”(来自Rest Framework快速入门)解析超链接关系的URL

ffx8fchx  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(130)

我正在学习rest框架的教程。我不知道这部分代码在apigroup上不起作用。请告诉我潜在的问题是什么。谢谢。
错误:

ImproperlyConfigured at /polls/users/
Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.

序列化程式:

from django.contrib.auth.models import User, Group
from rest_framework import serializers

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'groups']

class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ['url', 'name']

查看次数

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions
from .serializers import UserSerializer, GroupSerializer

class UserViewSet(viewsets.ModelViewSet):
    """ API endpoint that allows users to be viewed or edited """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]

class GroupViewSet(viewsets.ModelViewSet):
    """ API endpoint that allows groups to be viewed or edited """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    permission_classes = [permissions.IsAuthenticated]

URL数

from django.urls import path, include
from . import views
from rest_framework import routers

# for rest framework
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
xu3bshqb

xu3bshqb1#

尝试将basename添加到路由器寄存器:

router.register(r'snippets', SnippetViewSet, basename='snippet')
router.register(r'users', UserViewSet, basename='user')

相关问题