Django在保存new之前/之后删除新旧文件

时间:2017-01-20 15:12:43

标签: python django database

我在django视图中的代码:

file_obj = MyFile.objects.get(id=5)
old_preview = file_obj.preview_path
form = FilePreviewForm(request.POST, request.FILES, instance=file_obj)

if form.is_valid():
    print old_preview # /upload/files/hahaha.jpg
    print file_obj.preview_path # ololo.jpg
    # you can see different objects - it's good!

    old_preview.delete() # I want delete only /upload/files/hahaha.jpg - old file

    print old_preview #
    print file_obj.preview_path #
    # you can see all files are deleted!!! it's so bad!!!

为什么会这样?

如果我在保存后删除旧文件,它将是相同的。我查了一下!

UPD: http://pastebin.com/vB0SRzze - 它错了

UPD2: http://pastebin.com/bLNKbkLt

1 个答案:

答案 0 :(得分:1)

您没有保存表单,请先尝试执行此操作:

if form.is_valid():
    form.save()

有效吗?阅读here