non_field_errors : [“Expected a list of items but

2019-11-05 01:39发布

我使用的WebSocket前端(角度)后端(Django的)..我想在存储到数据库(MySQL的)消息创建实时聊天应用..当我试图从角商店消息Django的..它给我的错误:

non_field_errors:
["Expected a list of items but got type "dict"."]

这样有什么不好?

model.py

class msg(models.Model):
    name = models.ForeignKey(User, on_delete=models.CASCADE)
    receiver = models.CharField(max_length=20)
    text = models.CharField(max_length=1200)
    myDate = models.DateTimeField()

serializer.py

class MesSerializer(serializers.ModelSerializer):
    name = serializers.SlugRelatedField(many=False, slug_field='name', queryset=User.objects.all())
    class Meta:
        model = msg
        fields = '__all__'

view.py

class msg_list(APIView):
    def get(self, request, format=None):
        mes = msg.objects.all()
        serializer = MesSerializer(mes, many=True)  # convert into JSON
        return Response(serializer.data)

    def post(self, request, formate = None):
        serializer = MesSerializer(data=request.data, many = True) #type list
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

Answer 1:

麻烦的是不与塞。 这是你曾经使用过many = True在视图中,当您将数据传递到串行化,但你实际上只是发送一条消息-这就是为什么它是一个字典,而不是一个列表。 删除该参数。

def post(self, request, formate = None):
    serializer = MesSerializer(data=request.data)


文章来源: non_field_errors : [“Expected a list of items but got type ”dict“.”]