【问题标题】:Overwrite over a file and delete old model's object if the file exists如果文件存在,则覆盖文件并删除旧模型的对象
【发布时间】:2012-07-31 16:51:59
【问题描述】:

我做了一些东西来覆盖已经上传的文件:

class OverwriteStorage(FileSystemStorage):
def get_available_name(self, name):
    if self.exists(name):
        os.remove(os.path.join(settings.MEDIA_ROOT, name))
    return name

但我的文件在模型中:

class Work (models.Model):
    file = models.FileField(storage=OverwriteStorage(), upload_to=path)
    group = models.ForeignKey(Group, related_name='work_list')

新的上传又做了一个新的输入,所以我有:

  • 没有文件的模型(当我询问 file.size.. 时出现的错误)

  • 我的新模型

删除文件后如何删除模型?

我试图再次更改 FileSystemStorage 进程,但我不能使用任何参数(在文档中说并测试了几个小时;)),我也尝试更改保存进程,但我没有成功..

【问题讨论】:

    标签: django django-file-upload


    【解决方案1】:

    在继续进行故障排除之前需要检查一些事项:

    • 您是否在settings.py文件中设置了MEDIA_ROOT和MEDIA_URL?
    • 查看link 了解有关管理文件的更多信息
    • 我会利用 Django 的 built-in file storage 而不是从头开始构建一些东西

    【讨论】:

    • MEDIA_ROOT 和 MEDIA_URL 都可以
    • 我正在尝试做最小的改变,我很好:D
    【解决方案2】:

    我的解决方案:

    for work in groupwork : #It is the list of work associate with my group
        try :
           path = work.file.path.lstrip(SITE_ROOT+'/'+MEDIA_ROOT+'/').rstrip(request.FILES['file'].name)
           deletedwork = groupwork.get(file=path+request.FILES['file'].name)
           deletedwork.delete()
        except:
           pass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-16
      • 2016-03-01
      • 2015-11-25
      • 2020-08-18
      • 2015-02-02
      • 2012-08-11
      相关资源
      最近更新 更多