Django Rest Framework: The 'image' attribute has no file associated with it

2.4k views Asked by At

I'm using Django Rest Framework to create REST endpoints for a frontend. I have a model where there is the possibility of uploading 3 images (foto_1, foto_2, foto_3).

class Ocorrencia(TimeStampedModel):

(...)

foto_1 = models.ImageField("Foto 1", upload_to="ocorrencias/", blank=True)
foto_2 = models.ImageField("Foto 2", upload_to="ocorrencias/", blank=True)
foto_3 = models.ImageField("Foto 3", upload_to="ocorrencias/", blank=True)

My serializer is the following:

class OcorrenciaSerializer(GeoFeatureModelSerializer):

(...)

foto_1 = serializers.ImageField(allow_empty_file=True, allow_null=True, required=False, use_url=True)
foto_2 = serializers.ImageField(allow_empty_file=True, allow_null=True, required=False, use_url=True)
foto_3 = serializers.ImageField(allow_empty_file=True, allow_null=True, required=False, use_url=True)

class Meta:
    model = models.Ocorrencia
    geo_field = 'geometria'
    fields = ('foto_1', 'foto_2', 'foto_3')

If for example foto_3 has no file url associated in the database (it's saved as empty string when it's empty) then I get the following error when retrieving the associated endpoint:

Exception Value: The 'foto_3' attribute has no file associated with it.

Using allow_empty_file=True, allow_null=True, required=False when defining the serializer for the image fields seems to not do anything.

UPDATE 1

I found that this is related to using GeoFeatureModelSerializer, this is part of Django Rest Framework GIS. I'll have to seek a solution on that route. If I happen to use the default serializer class of DRF I have no issues. I was almost going insane with this issue. If I find a solution using GeoFeatureModelSerializer I'll post it here.

UPDATE 2

Updated Django-Rest-Framework-Gis to latest version and fixed it. Thank you all for your comments and suggestions.

0

There are 0 answers