How can I clear an image with DRF?

1,326 views
Skip to first unread message

Eric Palmitesta

unread,
Feb 10, 2018, 11:26:25 AM2/10/18
to Django REST framework
Hello, all!

I've posted my question to StackOverflow but the two responses there don't seem to resolve me issue.


class Part(models.Model):
    image
= models.ImageField(null=True, blank=True)

class PartSerializer(serializers.ModelSerializer):
   
class Meta:
        model
= Part
        fields
= ('id', 'image')

class PartDetail(generics.RetrieveUpdateAPIView):
    queryset
= Part.objects.all()
    serializer_class
= PartSerializer
    parser_classes
= (MultiPartParser, FormParser)

# put image, works fine
with tempfile.NamedTemporaryFile(suffix='.jpg') as fp:
    image
= Image.new('RGB', (100, 200))
    image
.save(fp)
    fp
.seek(0)
    data
= {'image': fp}
   
self.client.put('/path/to/endpoint', data, format='multipart')

# clear image, attempt #1
data
= {'image': None}
self.client.put('/path/to/endpoint', data, format='multipart')
# AssertionError: {'image': ['The submitted data was not a file. Check the encoding type on the form.']}

# clear image, attempt #2
data
= {'image': ''}
self.client.put('/path/to/endpoint', data, format='multipart')
# AssertionError: <ImageFieldFile: None> is not None

Using Django 1.11 and DRF 3.7, I'm sending a PUT to clear an image on a model by setting it to None, or empty-string, and getting back an error either way.  What's the "correct" way to clear an image from a model using DRF?

Eric Palmitesta

unread,
Feb 11, 2018, 10:53:28 AM2/11/18
to Django REST framework
Figured it out.  If I delete the image in perform_update before calling serializer.save(), then passing in {'image': ''} via PUT works fine:

class PartDetail(generics.RetrieveUpdateAPIView):
    queryset
= Part.objects.all()
    serializer_class
= PartSerializer
    parser_classes
= (MultiPartParser, FormParser
)
   
   
def perform_update(self, serializer):
        part
= Part.objects.get(pk=self.kwargs['pk'])
        part
.image.delete()
        serializer
.save()
Reply all
Reply to author
Forward
0 new messages