Save zip to FileField django

117 Views Asked by At

I have a view that create two csv and my goal is to zip them and add to a model.FileField

zip = zipfile.ZipFile('myzip.zip','w')
zip.writestr('file1.csv', file1.getvalue())
zip.writestr('file2.csv', file2.getvalue())

I have tried this, the zip is upload but when I download it I have the error 'the archive is damaged or unknown format'

Mymodel.objects.create(zip = File(open('myzip.zip','rb'))
1

There are 1 best solutions below

0
JPG On

This example just worked for me,

from django.core.files import File
from django.http import HttpResponse

from .models import ZipFile

import zipfile

from django.views import View


class ZipWriteView(View):
    def get(self, request, *args, **kwargs):
        with zipfile.ZipFile("myzip.zip", "w") as zip_obj:
            zip_obj.write("polls/views.py")  # add file 1
            zip_obj.write("polls/admin.py")  # add file 2

        with open(zip_obj.filename, "rb") as f:
            ZipFile.objects.create(file=File(f))
        return HttpResponse("Done")