“这个字段是必需的”POST到Django休息框架

时间:2016-01-11 20:30:44

标签: python django rest

我正在尝试使用httpie和以下语法POST到我的django rest框架序列化器:

http POST http://127.0.0.1:8000/traffic/geofences/ 
{
"id":13, 
"radius":40, 
"lat":0, 
"long":0, 
"name":"B"
}

返回以下错误:

{
"id":["This field is required."],
"name":["This field is required."],
"lat":["This field is required."],
"long":["This field is required."],
"radius":["This field is required."]
}

我不明白为什么不接受这些字段。格式应该是什么样的?服务器将从移动设备发送数据,并通过django rest框架将其插入数据库。 这是我的Serializer和Model and View

串行:

class GeofenceSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(min_value=0)
name = serializers.CharField()
lat = serializers.DecimalField(max_digits=10, decimal_places=6, coerce_to_string=False)
long = serializers.DecimalField(max_digits=10, decimal_places=6, coerce_to_string=False)
radius = serializers.IntegerField(min_value=0)
class Meta:
    model = Geofence
    fields = ('id', 'name','lat', 'long', 'radius')

def create(self, valid_data):
    return Geofence.objects.create(**valid_data)

型号:

class Geofence(models.Model):
id = models.IntegerField(default=0, primary_key=True)
name = models.CharField(max_length=200, default="Geofence", blank=False)
lat = models.DecimalField(default=0, decimal_places=6, max_digits=10, blank=False)
long = models.DecimalField(default=0, decimal_places=6, max_digits=10, blank=False)
radius = models.IntegerField(default=10, blank=False)

def __str__(self):
    return "Geofence: " + str(self.name);

查看:

class GeofencesView(APIView):
model = Geofence
serializer_class = GeofenceSerializer

def getId(self):
    return uuid.uuid4().int & (1<<64)-1

def get(self, request):
    fences = Geofence.objects.all()
    serializer = GeofenceSerializer(fences, many=True)
    return Response(serializer.data)

def post(self, request, format=None):
    serializer = GeofenceSerializer(data= request.data)
    serializer.id = -1
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors)

我已经阅读了django rest框架文档和django文档。 get请求正常。如果没有别的,我会很感激有人指着我在两个文档中讨论的地方。

1 个答案:

答案 0 :(得分:0)

我认为你没有为httpie使用正确的json格式。

请改为尝试:

http POST http://127.0.0.1:8000/traffic/geofences/ \
    id:=13 radius:=40 lat:=0 long:=0 name="B"