Update an ImageField that is uploaded to S3 - REST API - FormData

32 views Asked by At

I have created the following Django model:

def upload_image(user, filename):
    ext = filename.split('.')[-1]
    return '%s/user_image.%s' % (user.image_path, ext)

class CustomUser(AbstractUser):
    ...
    profile_picture = models.ImageField(default='default.png', upload_to=upload_image)

    @property
    def image_path(self):
        return f"{self.role}/{self.username}"

And I have installed the storage package with which I upload the photos to a S3 bucket with the following configurations:

if AWS_STORAGE_BUCKET_NAME' in os.environ:
    AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
    AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']
    AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME']
    AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
    AWS_S3_FILE_OVERWRITE = False

    STORAGES = {
        # Media file (image) management
        "default": {
            "BACKEND": "storages.backends.s3boto3.S3StaticStorage",
        },
        # CSS and JS file management
        "staticfiles": {
            "BACKEND": "storages.backends.s3boto3.S3StaticStorage",
        },
    }

When I create a new custom user, the photo is uploaded correctly.

if 'profile_picture' in self.validated_data:
    account.profile_picture = self.validated_data['profile_picture']
    account.save()

However, when I try to update the photo in the same way (with save), it does not work.

How upload_image is only called the first time when initiating the model ?

0

There are 0 answers