2

I have the following model in Django:

class AksOrder(models.Model):
    zip_file = models.FileField(upload_to='aks_zips/%M/%S/', blank=True)

and in my views I have in essential these functions:

def gen_zip(pk, name, vars):
    zipObj = ZipFile(os.path.join('/tmp/', str(name) + '_' + str(pk) + '.zip'), 'w')
    zipObj.write(pdf_files[0].path, '/filea.pdf')
    zipObj.write(pdf_files[1].path, '/fileb.pdf')

def aksorder_complete(request, pk):
    ao = get_object_or_404(AksOrder, id=pk)
    zipObj = generate_shop_zip(ao.c.pk, ao.dl, ao.vars)
    ao.zip_file.save('file.zip', zipObj)

I did not only try this version, but this one seems the most reasonable and logic one to me. I get a There is no item named 65536 in the archive. When I modify it slightly and close the file at the end of zip-writing in the first function, I get a ValueError: Attempt to use ZIP archive that was already closed message. Both times, the zip-File is generated properly in /tmp/ I could not work arount it. And that's only locally, I need to do it for S3 later...

zeus
  • 117
  • 7
  • You want to insert `images` in **Zipfile** ? – Lars Apr 15 '21 at 02:32
  • no, pdfs. as stated in line 3 and 4 from `gen_zip` function. It works. What I am asking basically is, how to save a zipflie to a `FileField` in django. I cannot make `Filefield = Zipfile`. – zeus Apr 15 '21 at 06:37

1 Answers1

2

I finally achieved it: I added a zipObj.close() to the first function at the end and I modified the 2nd function like so:

file = open('path/to/file.zip', 'rb')
ao.zip_file.save('name.zip', file)

apparently, the rb mode in file-open was decisive.

zeus
  • 117
  • 7