测试imageField

时间:2016-01-20 06:03:29

标签: python django django-rest-framework

我想测试我的观点,但我不知道如何在请求中发送图像。我的意思是,我有这样的模型:

class Item(models.Model):
    text = models.CharField(max_length=255)
    image = models.ImageField()

我有序列化器:

class RecieverSerializer(UserSerializer):
    class Meta():
        fields = ('id', 'email')
        extra_kwargs = {
            'username' : {'validators':[]}
        }

class ItemSerializer(serialisers.ModelSerializer):
    reciever = RecieverSerializer(many=True)
    class Meta():
        model = Item
        fields = ('text', 'image')

查看:

class ItemViewSet(viewsets.ModelViewSet):
    model = Item
    serializer_class = ItemSerializer
    queryset = []

如何将数据发送到服务器?如果我尝试json:

{ 
    "text": "123456",
    "reciever":[
        {"id":1, "email":"qwe@qwe.qwe"},
        {"id":2, "email":"asd@asd.asd"}
     ],
    "image" : http://someurl.com/way/image.jpg
}

Rest框架返回:JSON parse error - No JSON object could be decoded

1 个答案:

答案 0 :(得分:0)

试试看, 像这样编辑ItemSerializer

class ItemSerializer(serialisers.ModelSerializer):
    reciever = RecieverSerializer(many=True)
    image_url = serializers.SerializerMethodField(source='get_image_url')

    class Meta():
        model = Item
        fields = ('text', 'image')

    def get_image_url(self, obj):
        if obj.image:
            return self.context['request'].build_absolute_uri(obj.image.url)