gpt4 book ai didi

Python Django 不会用旧文件覆盖新上传的文件

转载 作者:行者123 更新时间:2023-12-01 01:47:45 25 4
gpt4 key购买 nike

我想在上传新文件时覆盖/替换文件。目前,该应用程序可以将文件上传到特定文件夹,但在上传新文件时不会覆盖文件。我需要帮助来解决这个问题。

View .py

def uploadfunc(request):
if request.method=='POST':
form =uploadfileform(request.POST,request.FILES)
if form.is_valid():
form.save()
return render_to_response('upload_successful.html')
else:
form=uploadfileform()
return render(request, 'upload.html',{'form':form})

模型.py

class uploadfolder(models.Model):
""" my application """
File_to_upload = models.FileField(upload_to='')

表单.py

class uploadfileform(forms.ModelForm):
class Meta:
model=uploadfolder
fields=('File_to_upload',)

最佳答案

您可以使用 Django pre_save 信号来实现此目的,如果文件存在,它将在保存之前删除该文件。

from django.db.models.signals import pre_save
from django.dispatch import receiver
import os

#It will activate whenever you will save file in uploadfolder model
@receiver(pre_save, sender=uploadfolder)
def file_update(sender, **kwargs):
upload_folder_instance = kwargs['instance']
if upload_folder_instance.id:
path = upload_folder_instance.file_to_upload.path
os.remove(path)

希望能有所帮助。

关于Python Django 不会用旧文件覆盖新上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51075396/

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