How to zip files ?

Recently I developed a project in Django
I have a site that has a form to upload the files which are then renamed with the uuids’ upload, but I would like to have the 3 files together in a zip.
I would like to be able to download each upload with the 3 files
How can I do this ?

class Upload(models.Model):
    uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    number = models.IntegerField(blank=True, null=True)
    def save_fatura(instance, filename):
        upload_to = ''
        ext = filename.split('.')[-1]
        filename = '{}_{}.{}'.format('fat',instance.uuid, ext)
        return os.path.join(upload_to, filename)
    def save_transferencia(instance, filename):
        upload_to = ''
        ext = filename.split('.')[-1]
        filename = '{}_{}.{}'.format('trf',instance.uuid, ext)
        return os.path.join(upload_to, filename)
    def save_contabilizacao(instance, filename):
        upload_to = ''
        ext = filename.split('.')[-1]
        filename = '{}_{}.{}'.format('cnt',instance.uuid, ext)
        return os.path.join(upload_to, filename)
    fatura = models.FileField(upload_to=save_fatura, null = True , blank = True )
    transferencia = models.FileField(upload_to=save_transferencia, null = True , blank = True )
    contabilizacao = models.FileField(upload_to=save_contabilizacao, null = True , blank = True )

Thanks for helping :slight_smile:

You can use the Python zipfile library to create a zip from the files that had been uploaded.

1 Like

Should I make a Zip field in the Models or a standard function ?

Ken Whitesell via Django Forum <notifications@djangoproject.discoursemail.com> escreveu no dia terça, 22/11/2022 à(s) 17:26:

I would probably make the file in the view where the files are uploaded. You could then either store it as another file or return it as the response from the post to that view.

1 Like

I made it work but there is other way to call the path without using C:User/etc ??
Exemple below
handle.write(f’C:/Users/user/Desktop/GesProj/core{fatura}', compress_type = zipfile.ZIP_DEFLATED)

Ken Whitesell via Django Forum <notifications@djangoproject.discoursemail.com> escreveu no dia terça, 22/11/2022 à(s) 17:57:

You may (should?) have a MEDIA_PATH already defined in your settings. You could use it as the base directory for what you create.

1 Like

I have. Thanks for helping Ken :slight_smile:

Ken Whitesell via Django Forum <notifications@djangoproject.discoursemail.com> escreveu no dia quarta, 23/11/2022 à(s) 12:27: