gpt4 book ai didi

python - 如何将文件从 FileField 复制到另一个具有不同上传路径 Django 的 FileField?

转载 作者:行者123 更新时间:2023-12-04 12:28:05 24 4
gpt4 key购买 nike

我正在使用 Django 来建立一个网站,我使用两个 FileField 一个供用户上传文档,另一个系统将把文档保存到它的备份中。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)
我使用了上面的代码但不起作用。
它只是为attachment_copy 提供attachment_number 字段的路径。
另外我想将文件上传到attachment_copy upload_to 路径。
请帮我解决这个问题。

最佳答案

这就是解决!
更改保存功能:

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)

关于python - 如何将文件从 FileField 复制到另一个具有不同上传路径 Django 的 FileField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68985552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com