【问题标题】:How to override FileField and automatically delete previous file in Django?如何覆盖 FileField 并自动删除 Django 中的先前文件?
【发布时间】:2011-08-22 20:19:49
【问题描述】:

我是 django 初学者 (django 1.2.5) 我有那个模型:

class Document(models.Model):
    file = models.FileField(upload_to='documents/%Y/%m/%d', null=True, blank=True)
    title = models.CharField(max_length=30)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    author = models.ForeignKey(User)
    #other fields
    #other fields

并以此为原型:

class DocumentForm(ModelForm):
    file = forms.FileField(required=True, error_messages={'required' : 'required!','empty': "empty!"})
    title = forms.CharField(widget = forms.TextInput(attrs={'size': 93,}), error_messages={'required': 'required!'})
   #other fields
   #other fields
    class Meta:
        model = Document
        exclude = ('author',)
def save(self, author, commit=True):
    document=ModelForm.save(self,commit=False)
    document.author = author
    if commit:
        document.save()
    return document

我使用上面的 DocumentForm 上传新文档,它工作得很好,但是当我尝试编辑一些文档时,我无法将新文件放在以前的位置。我可以更改除 FileField 之外的所有字段。

def document_edit(request, document_id):
    doc = get_object_or_404(Document, id=document_id)
    form = DocumentForm(instance=doc)
    if doc.author == request.user:
        if request.method == "POST":
            form = DocumentForm(request.POST, request.FILES, instance=doc)
            if form.is_valid():
                if request.POST.get('cancel'):
                   return HttpResponseRedirect('/')
                elif request.POST.get('delete'):
                    document = Document.objects.get(id=document_id)
                    document.file.delete()
                    document.delete()
                    return HttpResponseRedirect('/')
                else:
                    form.save(author=request.user)
                return HttpResponseRedirect('/')
            else:
                # return again form with errors
        else:
            # return form with doc instance
    else:
        # return "you can't edit this doc!"

我研究了 django 文档,我只知道我应该在某个类中编写一些自定义保存方法,但我完全不知道我该怎么做。应该是 Document() 还是 DocumentForm() 中的 save() 方法? 通常我想要这个:当我在表单中输入新文件的路径时,我想在他的位置覆盖这个新文件并自动删除以前的文件。

你能帮帮我吗?提前致谢!

【问题讨论】:

    标签: django django-models django-forms overriding uploading


    【解决方案1】:

    您在正确的轨道上,您只想使用instance 关键字,以便您的表单反映正在编辑的对象。简化版:

    def edit_upload(request, document_id):
        doc = get_object_or_404(Document, id=document_id)
        if request.method == 'POST': # If the form has been submitted...
            form = DocumentForm(request.POST, request.FILES, instance=doc)
            if form.is_valid(): # All validation rules pass
                if doc.file: # If document has file already...
                    doc.file.delete() # delete it
                form.save() # Saves object, uses new uploaded file
                return redirect('/thanks/') # Redirect after success
        else:
            form = DocumentForm(instance=doc) # Show form to edit
    
        return render(request, 'edit.html', {
            'form': form,
        })
    

    【讨论】:

    • 但我只想删除已存在的文件。此表格用于上传新文件。为什么 form.save() 不保存新文件?
    • 还是什么都没有!表格保存除文件以外的所有内容。我之前忘记了我添加的 DocumentForm 方法。也许这是问题: def save(self, author, commit=True): document=ModelForm.save(self,commit=False) document.author = author if commit: document.save() return document
    猜你喜欢
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 2019-12-27
    相关资源
    最近更新 更多