Django DRF image field does not accept null values

Viewed 416

Django DRF image field does not accept null values.

My model consists of image = models.ImageField(upload_to='uploads/', blank=True, null=True)

If I upload a file there's no problem. But, if I leave it blank it gives the following error:

The submitted data was not a file. Check the encoding type on the form.

I want to make the image field optional So I set null=True and blank=True. But this does not seem to work.

3 Answers

In DRF your model passes through serializer add this to your serializer:

class ImagePostSerializer(serializers.ModelSerializer):
    image = serializers.ImageField(required=False)
    class Meta:
        model = models.ImagePost

Use the DRF Imagefield in serializer

serializers.ImageField(required=False)

DRF ImageField is validating the uploaded file content as matching a known image format. Corresponds to django.forms.fields.ImageField

ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)

Refer: https://www.django-rest-framework.org/api-guide/fields/#imagefield

I got the solution. I was using a different serializer to create an instance of that model. I removed the serializer and now it is working.

Related