django.core.exceptions.ImproperlyConfigured:无法使用视图名称" user-detail"解析超链接关系的URL [英] django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail"
问题描述
TL; DR:我收到此错误并且不知道原因:
TL;DR: I am getting this error and don't know why:
django.core.exceptions.ImproperlyConfigured:Could不使用视图名称user-detail解析超链接关系的URL。您可能未能在API中包含相关模型,或者在此字段上错误地配置了lookup_field属性。
django.core.exceptions.ImproperlyConfigured: 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.
我是浏览 django-rest-framework教程目前处于基于功能的视图(FBV)切换到class,mixin和基于通用的视图(分别为CBV,MBV,GBV)的点。切换到GBV后,当我去测试我的API时,我收到了这个错误 AssertionError:使用名为pk的URL关键字参数调用预期视图SnippetDetail。修复您的URL conf,或在视图上正确设置'.lookup_field'属性。
。我做了一些研究,发现 lookup_field
需要设置为urlpatterns中的。目前,我的urls.py看起来像这样:
I am going through the django-rest-framework tutorial and am currently at a point where function based views (FBV) were switched to class, mixin, and generic based views (CBV, MBV, GBV respectively). After switching to GBV, when I went to test my API, I received this error AssertionError: Expected view SnippetDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the '.lookup_field' attribute on the view correctly.
. I did some research and found that lookup_field
needs to be set to the in the urlpatterns. Currently, my urls.py look like this:
from django.conf.urls import url, include
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
# API endpoints
urlpatterns = format_suffix_patterns([
url(r'^$', views.api_root),
url(r'^snippets/$',
views.SnippetList.as_view(),
name='snippet-list'),
url(r'^snippets/(?P<id>[0-9]+)/$',
views.SnippetDetail.as_view(),
name='snippet-detail'),
url(r'^users/$',
views.UserList.as_view(),
name='user-list'),
url(r'^users/(?P<id>[0-9]+)/$',
views.UserDetail.as_view(),
name='user-detail')
])
# Login and logout views for the browsable API
urlpatterns += [
url(r'^auth/', include('rest_framework.urls',
namespace='rest_framework')),
]
和我的views.py看起来像这样:
and my views.py look like so:
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer, UserSerializer
from snippets.permissions import IsOwnerOrReadOnly
from rest_framework import generics
from rest_framework import permissions
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from django.contrib.auth.models import User
@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 UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly, )
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly, )
当我在UserDetail和SnippetDetail中添加 lookup_field ='id'
时,异常会自行解决。 (好极了!)。但是,当我访问 http://127.0.0.1/users/1/ ImproperlyConfigured:无法使用视图名称user-detail解析超链接关系的URL。您可能未能在API中包含相关模型,或者在此字段上错误地配置了lookup_field属性。
将被抛出。但是,当我检查控制台时,还有第二个例外:
when I add lookup_field = 'id'
in both UserDetail and SnippetDetail, the exception resolves itself. (Yay!). But, when I visit http://127.0.0.1/users/1/ ImproperlyConfigured: 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.
is thrown. When I check the console, however, there is a second exception:
django.urls.exceptions.NoReverseMatch:反向'用户详细信息'找不到
参数'()'和关键字参数'{'pk':1}'。 2
模式尝试:['用户/(?P [0-9] +)\。(?P [a-z0-9] +)/?$',
' users /(?P [0-9] +)/ $']
django.urls.exceptions.NoReverseMatch: Reverse for 'user-detail' with arguments '()' and keyword arguments '{'pk': 1}' not found. 2 pattern(s) tried: ['users/(?P[0-9]+)\.(?P[a-z0-9]+)/?$', 'users/(?P[0-9]+)/$']
在处理上述异常期间,发生了另一个异常:
During handling of the above exception, another exception occurred:
django.core.exceptions.ImproperlyConfigured:无法使用视图名称user-detail解析
超链接关系的URL。您可能有
未能在API中包含相关模型,或者错误地
在此字段上配置了'lookup_field'属性。
django.core.exceptions.ImproperlyConfigured: 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.
我觉得有趣的是第一个例外的kwargs是 {'pk':1}
,而不是 {'id :1}
。在聊天的帮助下,有人指我这个一条信息:
What I find interesting is that the kwargs for the first exception is {'pk': 1}
, not {'id':1}
. After some help from chat, someone pointed me to this piece of information:
请注意,使用超链接API时,您需要确保API视图和序列化程序类都设置如果您需要使用自定义值,则查找字段。
Note that when using hyperlinked APIs you'll need to ensure that both the API views and the serializer classes set the lookup fields if you need to use a custom value.
这对于用户$ c非常有用$ c>序列化程序扩展
HyperlinkedModelSerializer
:
This is useful as User
serializer extends HyperlinkedModelSerializer
:
from rest_framework import serializers
from django.contrib.auth.models import User
from snippets.models import Snippet
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')
用户
模型和序列化程序与 Snippet
具有反向关系。现在,当我将 lookup_field ='id'
添加到 UserSerializer的片段属性
( snippets = serializers.HyperlinkedRelatedField(many = True,view_name ='snippet-detail',read_only = True,lookup_field ='id')
),就像它要求我这样做这里,错误是持久的。
the User
model and serializer has a reverse relationship with Snippet
. Now, when I add lookup_field='id'
to snippets attribute of UserSerializer
(snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True, lookup_field='id')
), like it asks me to do so here, the error is persistent.
我做错了什么?我该怎么做才能解决这个问题?它与 lookup_id
没有任何关系吗?
What am I doing incorrectly? What can I do to fix this? Is it not having anything to do with lookup_id
?
我知道我可以替换 < id>
在我的urlpatterns中使用< pk>
,但我想了解为什么这种情况正在发生。
I understand that I could replace <id>
with <pk>
in my urlpatterns, but I would like to understand why this is happening.
推荐答案
我最终通过在Django shell / python交互式控制台中打印序列化程序修复了我的第二个异常。我得到的结果是:
I eventually fixed my second exception by printing the serializer in the Django shell/python interactive console. The result I got was this:
>>> from snippets.serializers import UserSerializer
>>> print(UserSerializer())
UserSerializer():
url = HyperlinkedIdentityField(view_name='user-detail')
id = IntegerField(label='ID', read_only=True)
username = CharField(help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, validators=[<django.contrib.auth.validators.UnicodeUsernameValidator object>, <UniqueValidator(queryset=User.objects.all())>])
snippets = HyperlinkedRelatedField(lookup_field='id', many=True, read_only=True, view_name='snippet-detail')
事实证明,改变< pk> $在urlspatterns中,您需要添加
url = HyperlinkedIdentityField(view_name ='user-detail',lookup_field ='
。 UserSerializer
类中的id')
It turns out that to change <pk>
to <id>
in urlspatterns, you need to add url = HyperlinkedIdentityField(view_name='user-detail', lookup_field='id')
in the UserSerializer
class.
这篇关于django.core.exceptions.ImproperlyConfigured:无法使用视图名称" user-detail"解析超链接关系的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!