Axil
Axil

Reputation: 3311

Django image attribute has no file associated with it REST API

I have a model Employee with an ImageField, and I return REST API response of the model but it shows this error

The 'face_image' attribute has no file associated with it.

My API generates a response this way: https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py

@api_view(['GET'])
def get_employee(request):
    data = [emp.as_dict() for emp in Employee.objects.all()]
    return Response(data, status=status.HTTP_200_OK) 

The following is the model:

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py

class Employee(models.Model):
    ...
    face_image = models.ImageField(upload_to='face_image/', blank=True)

    def face_image_url(self):
        if self.face_image and hasattr(self.face_image, 'url'):
            return self.face_image.url

    def as_dict(self):
        return {"id":self.id,
                ...
                "face_image":self.face_image.url, <-- causes no file associated
                ...}

How do I solve this REST response handling imagefield without file ? I tried to follow some ways in here Django The 'image' attribute has no file associated with it but I cant accomplish with the helper function.

If I remove the imagefield, it will generate a response this way https://i.sstatic.net/yLjrH.jpg. But I want the imagefield to be in the structure, how to handle in this does not exist file situation

Upvotes: 0

Views: 1914

Answers (2)

Cl&#233;ment Denoix
Cl&#233;ment Denoix

Reputation: 1514

Here:

"face_image":self.face_image.url, <-- causes no file associated

You don't actually use your face_image_url method.

It should be:

`"face_image":self.face_image_url()

As I said above, I think it's really a bad idea to handle the serialization of your model like you did. I strongly advise you to take a look at the serializers.

Upvotes: 0

Mohammad Mustaqeem
Mohammad Mustaqeem

Reputation: 1084

You need to explicitly handle this case. In this case, your as_dict method should look like:

def as_dict(self):
    return {"id":self.id,
            ...
            "face_image": self.face_image.url if self.face_image else None
            ...}

Upvotes: 2

Related Questions