用django休息框架发布图像

时间:2014-05-14 19:30:59

标签: django api django-rest-framework

我正在尝试为海洋船只和船只做一个简单的api,我正在使用django-rest-framework作为库来生成api。对于模型级别中包含char字段和整数等简单字段的模型,一切正常(创建,删除,更新,列表,获取)。

每当我尝试发布包含未检测到图像的记录时,问题就出现在图像字段上。并且它总是会导致错误“序列项1:期望的字符串,找到NoneType”

下面是我的模型,序列化程序和视图文件。 串行化

class VesselSerializer(serializers.ModelSerializer):
    image = serializers.ImageField(source='image')
    class Meta:
        model = Vessel
        fields = ('image', 'id', 'vesselType', 'name')

class VesselTypeSerilizer(serializers.ModelSerializer):
    class Meta:
        model = VesselType

模型

def vessel_file_name(instance, filename):
    return '/'.join(['vessels', instance.id, filename]) #the error is in this line

class VesselType(models.Model):
    name = models.CharField(max_length=50)    

class Vessel(models.Model):
    name = models.CharField(max_length=50)
    vesselType = models.ForeignKey(VesselType)
    image = models.ImageField(upload_to=vessel_file_name, null=True)

    def __unicode__(self):
        return u'%s' % self.name

视图

class VesselList(generics.ListCreateAPIView):
    queryset = Vessel.objects.all()
    serializer_class = VesselSerializer
    fields = ('url', 'id', 'image', 'vesselType')

    def post(self, request, format=None):
        print 'entered here'
        print '%' * 10
        print request.DATA
        print request.FILES
        print '%' * 10
        serializer = VesselSerializer(data=request.DATA, files=request.FILES)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class VesselDetails(generics.RetrieveUpdateDestroyAPIView):
    queryset = Vessel.objects.all()
    serializer_class = VesselSerializer

应该注意的是,打印时的request.FILES和request.DATA正确显示但是出现错误,表明没有文件名,尽管名称出现在request.FILES中。

我在这个问题上陷入了几个小时,我似乎无法找到问题是什么或我做错了什么。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

问题是,当调用vessel_file_name时,instance对象不会保存到数据库,instance.idNone