如何在 Django 中覆盖 FileField 并自动删除以前的文件?

发布于 2024-11-06 11:07:42 字数 2243 浏览 1 评论 0原文

我是 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()中的save()方法还是DocumentForm()中的save()方法? 一般来说,我想要这个:当我在表单中输入新文件的路径时,我想在他的位置覆盖这个新文件并自动删除以前的文件。

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

im django beginner (django 1.2.5)
I have that model:

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

and model form to this:

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

I uploading new documents in using DocumentForm above and it works pretty but when i trying edit some document i cannot put new file in place previous. I may change every field except 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!"

I research django documentation and i only know i should write some custom save method in some class but i completely have no idea how can i do this. It should be save() method in Document() or in DocumentForm()?
Generally i want this: When i put path to new file in form i want override this new file in his place and automatically delete previous file.

Can you help me? Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我很OK 2024-11-13 11:07:42

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

You are on the right track, you just want to use the instance keyword, so your form reflects the object being edited. Simplified version:

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,
    })
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文