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

时间:2018-06-28 05:40:10

标签: python django django-views

我想在每次上传新文件时覆盖/替换文件。当前,该应用程序可以将文件上传到特定的文件夹,但是如果已经上传了新文件,则该应用程序不能覆盖文件。我需要协助来解决这个问题。

views.py

=C1-B1

models.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})

forms.py

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

2 个答案:

答案 0 :(得分:0)

您可以使用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)

希望这会有所帮助。

答案 1 :(得分:0)

感谢@vermanil我的更新模型。py对我有用。

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

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

@receiver(pre_save, sender=uploadfolder)
def file_update(sender, **kwargs):
    upload_folder_instance = kwargs['instance']
    if upload_folder_instance.File_to_upload:
        path = upload_folder_instance.File_to_upload.path
        os.remove(path)