gpt4 book ai didi

python - 无法使用 View 名称 "book-detail"解析超链接关系的 URL

转载 作者:行者123 更新时间:2023-12-04 08:46:27 26 4
gpt4 key购买 nike

以前我用的是 ModelSerializer并且没有错误。当我用 HyperlinkedModelSerializer 替换它时这个错误被抛出

Could not resolve URL for hyperlinked relationship using view name "book
detail". You may have failed to include the related model in your API,
or incorrectly configured the `lookup_field` attribute on this field.
这是 serializers.py文件:
class BookSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Book
fields = ['id', 'url', 'title', 'subtitle', 'isbn']
model.py
class Book(models.Model):
title = models.CharField(max_length=250)
subtitle = models.CharField(max_length=250)
author = models.CharField(max_length=100)
isbn = models.CharField(max_length=13)

def __str__(self):
return self.title
views.py
class BookListView(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
urls.py
router = routers.DefaultRouter()
router.register('books', BookListView)


app_name = "books"
urlpatterns = [
path('', include(router.urls)),
]
View 名称 book-detail在我的 View 中不存在,可能是 Django 自动创建的,我不知道在哪里可以找到和调试它?谢谢你。
这是错误的追溯 -
Environment:


Request Method: GET
Request URL: http://localhost:8000/books/

Django Version: 3.1.2
Python Version: 3.8.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'books.apps.BooksConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
File "D:\All\Back-end Django\REST API Django\lib\site-packages\rest_framework\relations.py", line 398, in to_representation
url = self.get_url(value, self.view_name, request, format)
File "D:\All\Back-end Django\REST API Django\lib\site-packages\rest_framework\relations.py", line 336, in get_url
return self.reverse(view_name, kwargs=kwargs, request=request, format=format)
File "D:\All\Back-end Django\REST API Django\lib\site-packages\rest_framework\reverse.py", line 47, in reverse
url = _reverse(viewname, args, kwargs, request, format, **extra)
File "D:\All\Back-end Django\REST API Django\lib\site-packages\rest_framework\reverse.py", line 60, in _reverse
url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
File "D:\All\Back-end Django\REST API Django\lib\site-packages\django\urls\base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "D:\All\Back-end Django\REST API Django\lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix
raise NoReverseMatch(msg)

During handling of the above exception (Reverse for 'book-detail' not found. 'book-detail' is not a valid view function or pattern name.), another exception occurred:
File "D:\All\Back-end Django\REST API Django\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "D:\All\Back-end Django\REST API Django\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\All\Back-end Django\REST API Django\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "D:\All\Back-end Django\REST API Django\lib\site-packages\rest_framework\viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "D:\All\Back-end Django\REST API Django\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "D:\All\Back-end Django\REST API Django\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "D:\All\Back-end Django\REST API Django\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "D:\All\Back-end Django\REST API Django\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "D:\All\Back-end Django\REST API Django\lib\site-packages\rest_framework\mixins.py", line 46, in list
return Response(serializer.data)
File "D:\All\Back-end Django\REST API Django\lib\site-packages\rest_framework\serializers.py", line 745, in data
ret = super().data
File "D:\All\Back-end Django\REST API Django\lib\site-packages\rest_framework\serializers.py", line 246, in data
self._data = self.to_representation(self.instance)
File "D:\All\Back-end Django\REST API Django\lib\site-packages\rest_framework\serializers.py", line 663, in to_representation
return [
File "D:\All\Back-end Django\REST API Django\lib\site-packages\rest_framework\serializers.py", line 664, in <listcomp>
self.child.to_representation(item) for item in iterable
File "D:\All\Back-end Django\REST API Django\lib\site-packages\rest_framework\serializers.py", line 515, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "D:\All\Back-end Django\REST API Django\lib\site-packages\rest_framework\relations.py", line 413, in to_representation
raise ImproperlyConfigured(msg % self.view_name)

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

最佳答案

我也曾经遇到过这个问题,但我通过这样做解决了这个问题:
urls.py(项目)
您可能需要在 root urls.py 中为您的应用程序提供命名空间

path('your_url', include(('your_app.urls', 'your_app'), namespace="your_app"))
serializers.py
添加 HyperlinkedIdentityField
class BookSerializer(serializers.HyperlinkedModelSerializer):
# add this
url = serializers.HyperlinkedIdentityField(view_name="your_app:book-detail")

class Meta:
model = Book
fields = ['id', 'url', 'title', 'subtitle', 'isbn']
urls.py (应用程序)
添加 basename
router = routers.DefaultRouter()
# add basename
router.register('books', BookListView, basename="books")
文档 https://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/

关于python - 无法使用 View 名称 "book-detail"解析超链接关系的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64290220/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com