教程5:关系和超链接API错误教程链接地址是:https://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/我尝试了查询相关的解决方案,在stackoverflow上也遇到了类似的问题,但经过测试,我仍然无法使用它们。
views.py
class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class SnippetDetail(generics.RetrieveDestroyAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
@api_view(['GET'])
def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request, format=format),
'snippets': reverse('snippet-list', request=request, format=format),
})
class SnippetHighlight(generics.GenericAPIView):
queryset = Snippet.objects.all()
renderer_classes = [renderers.StaticHTMLRenderer]
def get(self, request, *args, **kwargs):
snippet = self.get_object()
return Response(snippet.highlighted)
urls.py
urlpatterns = format_suffix_patterns([
path('', views.api_root),
path('snippets/', views.SnippetList.as_view(), name='snippet-list'),
path('snippets/<int:pk>/', views.SnippetDetail.as_view(), name='snippet-detail'),
path('snippets/<int:pk>/highlight/', views.SnippetHighlight.as_view(), name='snippet-highlight'),
path('users/', views.UserList.as_view(), name='user-list'),
path('users/<int:pk>/', views.UserDetail.as_view(), name='user-detail'),
])
urlpatterns += [
path(r'api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
serializers.py
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')
class Meta:
model = Snippet
fields = ['url', 'id', 'highlight', 'owner',
'title', 'code', 'linenos', 'language', 'style']
class UserSerializer(serializers.HyperlinkedModelSerializer):
snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True)
class Meta:
model = User
fields = ['url', 'id', 'username', 'snippets']
追溯错误:
Traceback:
File "C:\Anaconda3\envs\python36\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request)
File "C:\Anaconda3\envs\python36\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request)
File "C:\Anaconda3\envs\python36\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Anaconda3\envs\python36\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 54. return view_func(*args, **kwargs)
File "C:\Anaconda3\envs\python36\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs)
File "C:\Anaconda3\envs\python36\lib\site-packages\rest_framework\views.py" in dispatch 505. response = self.handle_exception(exc)
File "C:\Anaconda3\envs\python36\lib\site-packages\rest_framework\views.py" in handle_exception 465. self.raise_uncaught_exception(exc)
File "C:\Anaconda3\envs\python36\lib\site-packages\rest_framework\views.py" in raise_uncaught_exception 476. raise exc
File "C:\Anaconda3\envs\python36\lib\site-packages\rest_framework\views.py" in dispatch 502. response = handler(request, *args, **kwargs)
File "C:\Anaconda3\envs\python36\lib\site-packages\rest_framework\decorators.py" in handler 50. return func(*args, **kwargs)
File "C:\Users\Ze Ran Lu\Desktop\swie\text\tutorials\snippets\views.py" in api_root 205. 'users': reverse('user-list'),
File "C:\Anaconda3\envs\python36\lib\site-packages\rest_framework\reverse.py" in reverse 47. url = _reverse(viewname, args, kwargs, request, format, **extra)
File "C:\Anaconda3\envs\python36\lib\site-packages\rest_framework\reverse.py" in _reverse 60. url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
File "C:\Anaconda3\envs\python36\lib\site-packages\django\urls\base.py" in reverse 90. return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Anaconda3\envs\python36\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix 622. raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at / Exception Value: Reverse for 'user-list' not found. 'user-list' is not a valid view function or pattern name.
4条答案
按热度按时间afdcj2ne1#
另一个url.py文件是
iezvtpos2#
项目结构
教程|_片段||_urls.py||_views.py||_models.py||_apps.py||_admin.py|_教程|_urls.py|_settings.py|_wsgi.py
mqxuamgl3#
添加这行代码
in snippets/urls.py
对我有帮助。zsbz8rwp4#
reverse只接受这些参数:
reverse(viewname,urlconf=None,args=None,kwargs=None,current_app=None)
你的
users/
不接受任何参数,所以你只需要反向的url名称