Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin ImageField: Upload a valid image. The file you uploaded was either not an image or a corrupted image

ERROR: "Upload a valid image. The file you uploaded was either not an image or a corrupted image."

I have been looking around and I haven't been able to find a solution to my problem. I use the same images locally in a venv and they work. I use the same images in a docker container that has the same Pillow library and dependancies and it works.

I have a Django ImageField that I have a simple admin form.

I can get the images to upload to S3 for storage. I have pulled the docker container we use on the servers and I have ran this locally, but is cannot get the error. I have not run into this error before with image uploading, so I am unsure why this is happening.

# models.py
@deconstructible
class RandomFileName(object):

    def __init__(self, path):
        self.path = path

    def __call__(self, instance, filename):
        ext = filename.split('.')[-1]
        filename = '{}.{}'.format(uuid.uuid4().hex, ext)

        return os.path.join(self.path, filename)

class MyModel(models.Model):
    name = models.CharField(max_length=50)
    avatar = models.ImageField(
        upload_to=RandomFileName('avatars')
    )
    ...


# admin.py
@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    list_display = (
        'name',
        ...
    )
    fieldsets = (
        (None, {'fields': (
            'name',
            'avatar',
        )}),
    )
    ...

Dependancies:

Django==2.0.3

Pillow==5.3.0

Edit:

This is behind AWS API Gateway and my answer/solution is below if anyone should encounter this issue themselves.

like image 483
MTCodexus Avatar asked Dec 15 '18 01:12

MTCodexus


2 Answers

I solved this yesterday! There is nothing wrong with the code itself or the packages.

One thing I forgot to mention is that this is behind API Gateway and so I needed to modify that to accept "multipart/form-data".

like image 61
MTCodexus Avatar answered Nov 10 '22 13:11

MTCodexus


Had the same/similar issue, this resolved it:

  1. Add multipart/form-data to API Gateway Settings under Binary Media Types
  2. In proxy "Method Request", "HTTP Request Headers" add "Accept" and "Content-Type"
  3. RE-DEPLOY API
like image 1
monkut Avatar answered Nov 10 '22 14:11

monkut