How to copy file from FileField to another FileField with different upload path Django?

Viewed 70

I am using Django to build a website and I am using two FileField one for user to upload the document ant the other the system will take the document to save a backup of it.

My Model

def file_path_dir(instance, filename):
        return "File/{0}/{1}".format("File" + datetime.now().strftime("%Y.%m.%d"), filename)

def file_path_dir_copy(instance, filename):
     
        return "FileBackUp/{0}/{1}".format("FileBackUp" + datetime.now().strftime("%Y.%m.%d"), filename)
class MyModal(models.Model)
    UPLOAD_ROOT = "C:/"
    UPLOAD_COPY = "C:/"
    upload_storage = FileSystemStorage(location=UPLOAD_ROOT, base_url="/uploads")
    upload_storage_copy = FileSystemStorage(location=UPLOAD_COPY, base_url="/uploads")

    attachment_number = models.FileField(
        verbose_name=_("Attachment"),
        upload_to=file_path_dir,
        storage=upload_storage,
        blank=True,
        null=True,
    )
    attachment_copy = models.FileField(
        verbose_name=_("Backup Attachment"),
        upload_to=file_path_dir_copy,
        storage=upload_storage_copy,
        blank=True,
        null=True,
    )

My save view function

def save_model(self,request,obj,*args,**kwargs):
        print(obj)
        for sub_obj in obj:
            path = sub_obj.file_path_dir_copy(sub_obj.attachment_number.name)
            sub_obj.attachment_copy=path
        return super(AttachmentFormsetView,self).save_model(request,obj,*args,**kwargs)

I used the code above but does not work.

It just give the attachment_copy the path of the attachment_number field.

Also I want to upload file to the attachment_copy upload_to path.

Please help me solving this problem.

1 Answers

this is solve! change in your save function:

def save_model(self,request,obj,*args,**kwargs):

    from django.core.files.storage import FileSystemStorage
    for sub_obj in obj:
        fs = FileSystemStorage(location= "C:/FileBackup/{0}".format("FileBackup" + datetime.now().strftime("%Y.%m.%d")),base_url="/uploads")
        filename = fs.save(sub_obj.attachment_number.name, sub_obj.attachment_number)
        file_url = fs.url(filename)
        path = sub_obj.file_path_dir_copy(sub_obj.attachment_number.name)
        sub_obj.attachment_copy=path
    return super(AttachmentFormsetView,self).save_model(request,obj,*args,**kwargs)
Related