• Django: AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer.


    错误翻译

    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')
    不考虑业务场景,一味的争执技术的高下,都是耍流氓。
  • 相关阅读:
    Mybatis使用resultType实现一对一查询
    利用webSocket使网页和服务器通信
    hdu--1728--special bfs
    hdu--1429--状压bfs
    hdu--3006--不知为何wa
    hdu--3001--类似旅行商<tsp>
    hdu--2660--二维费用背包
    hdu--4632--dp
    hdu--4497--数论
    hdu--4496--并查集
  • 原文地址:https://www.cnblogs.com/leoych/p/15033939.html
Copyright © 2020-2023  润新知