[Django]-Django – generate Zip file and serve (in memory)


You make the very rookie mistake of not calling close / closing the file (ZipFile here) after opening it, best use the ZipFile as a context manager:

def generate_images_zip(self) -> bytes:
    content = BytesIO()
    with ZipFile(content, 'w') as zipObj:
        for image_fieldname in self.images_fieldnames():
            image = getattr(self, image_fieldname)
            if image:
                zipObj.writestr(image.name, image.read())
    return content.getvalue()

Leave a comment