Home:ALL Converter>Can't save InMemoryUploadedFile to S3 in Django Admin

Can't save InMemoryUploadedFile to S3 in Django Admin

Ask Time:2022-02-22T03:16:31         Author:andrepz

Json Formatter

I'm using the django-storage package, and trying to upload multiple images at once. So I overwritten the add_view and save_model methods in ModelAdmin, in order to remove the original image field and use a custom one (with a multiple flag in the input tag) given in the template HTML:


class Media(AbstractCreatedUpdatedDateMixin):
    uuid = models.UUIDField(unique=True, default=uuid4, editable=False, db_index=True)
    user = models.ForeignKey(User, related_name="uploaded_media", on_delete=models.CASCADE)
    title = models.CharField(max_length=255)
    image = models.ImageField(upload_to=uuid_directory_path)


class MediaModelAdmin(admin.ModelAdmin):
    def add_view(self, request, form_url='', extra_context=None):
        self.exclude = ('image', "is_approved")
        extra_context = extra_context or {}
        extra_context['show_save_and_add_another'] = False
        extra_context['show_save_and_continue'] = False
        return super().add_view(request, form_url, extra_context)

    def save_model(self, request, obj, form, change):
        for file in request.FILES.values():
            obj.user = User.objects.filter(id=request.POST.get("user")).first()
            obj.title = request.POST.get("title")
            obj.image.save(file.name, file.file)

It uploads correctly to S3, but it doesn't save the instance and throws this error:

TypeError at /admin/media/media/add/
expected string or bytes-like object

I'm not sure what is wrong here, maybe the fact that the upload is not done yet so the DB transaction is rolled back, but I can't figure out what do to.

Author:andrepz,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/71211850/cant-save-inmemoryuploadedfile-to-s3-in-django-admin
Olga Riabukha :

Try to change this\n\nobj.image.save(file.name, file.file)\n\nto\nobj.image.save(file.name, file)\n",