Reputation: 470
I am trying to make a simple api for marine vessels and ships and I am using django-rest-framework as the library to generate the api. With models that has simple fields like char fields and integers in the models level everything is working properly (create, delete, update, list, get).
The problem is with image fields whenever I try to post a record that has images it does not detect it. And it always causes an error "sequence item 1: expected string, NoneType found"
Below is my model, serializer, and view files. serializer
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
models
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
views
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
It should be noted as well that the request.FILES and request.DATA when printed are displayed correctly yet that error appears which indicates that there is no file name although the name appears in request.FILES.
I am stuck in this problem for several hours and I can't seem to find what the problem is or what I am doing wrong. Any help would be appreciated.
Upvotes: 0
Views: 2684
Reputation: 2415
The problem is that when vessel_file_name
is called, the instance
object is not saved to the db and instance.id
is None
.
Upvotes: 1