错误翻译
AssertionError: ' HyperlinkedIdentityField '需要在序列化器上下文中请求。在实例化序列化器时添加' context={'request': request} '。
错误代码:
book_ser = BookSerializer(data=request.data)
修改后:
book_ser = BookSerializer(data=request.data, context={'request': request})
全部代码
# views.py @api_view(['GET', 'POST']) def books(request): if request.method == 'GET': return Response(data={"msg": "get ok"}) elif request.method == "POST": book_ser = BookSerializer(data=request.data, context={'request': request}) if book_ser.is_valid(): book_ser.save() return Response(book_ser.data) return Response(data={'msg': 'error'}, status=status.HTTP_400_BAD_REQUEST)
报了一个新的错误
django.core.exceptions.ImproperlyConfigured: 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.
上述问题,我引入HyperlinkedModelSerializer方法,重启服务器已解决
# models.py
from rest_framework import serializers
from RESTSerializer.models import Book
class BookSerializer(serializers.HyperlinkedModelSerializer): """ 对数据库进行序列化 """ class Meta: model = Book fields = ('b_name', 'b_price')