无效数据。期望有字典,但有字节

时间:2019-05-29 07:25:53

标签: django-rest-framework

当我请求保存API时,出现以下错误: {     “ non_field_errors”:[         “无效的数据。应为字典,但有字节。”     ] }

models.py

from django.db import models

# Create your models here.
class employee(models.Model):
    name=models.CharField(max_length=10)
    surname=models.CharField(max_length=10)
    emo_id=models.IntegerField()

    class Meta:  
        db_table = "employee" 

    def __str__(self):
        return self.name

serializer.py
from rest_framework import serializers
from .models import employee

class convertSerializers(serializers.ModelSerializer):
    class Meta:
        model = employee
        fields = '__all__' # for all field

views.py

def saveEmployee(request):
    serializer = convertSerializers(data=request.body)
    print(serializer)
    if request.method == 'POST':
        if serializer.is_valid():
            serializer.save()
            return JsonResponse('saved successfull', safe=False)
        return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

1 个答案:

答案 0 :(得分:2)

由于使用的是DRF,因此可以使用request.data代替 request.body

from rest_framework.decorators import api_view
from rest_framework.response import Response


@api_view(['POST'])
def saveEmployee(request):
    serializer = convertSerializers(data=request.data)
    serializer.is_valid(True)
    serializer.save()
    return Response('saved successful')