如何覆盖FileField并自动删除Django中的上一个文件?

时间:2011-05-10 21:43:56

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

im 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()方法吗? 一般我想要这个:当我把路径放到表格中的新文件时,我希望在他的位置覆盖这个新文件并自动删除以前的文件。

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

1 个答案:

答案 0 :(得分:0)

您走在正确的轨道上,您只想使用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,
    })