使用文件字段编辑 Django 模型而不重新上传文件

Posted

技术标签:

【中文标题】使用文件字段编辑 Django 模型而不重新上传文件【英文标题】:Editing a Django model with a filefield without re-uploading the file 【发布时间】:2013-07-20 10:10:51 【问题描述】:

下面是我项目中django代码的简化版本;它允许用户上传文件并给它一个标题。此功能完美运行。但是,当用户稍后重新编辑表单时,文件和标题会重新显示,但是当用户去提交文件时,文件是空的。重新打开以进行编辑的表单的文件字段如下所示:

目前: media_location/uploadedfile.mp3

更改: [选择文件] 未选择文件

我提交后是:

此文件为必填项

[选择文件] 未选择文件

如何获取它以便用户不必重新上传文件?提交完成后是否将该字段设为只读,或者是否保持可编辑对我来说并不重要。完成的项目不适用于客户,并且只提供给一小部分受信任的用户,但如果可能的话,我仍然希望遵循最佳实践。感谢您的帮助。

Django 代码:

models.py

class Recording(models.Model):
    rec_title=models.CharField(max_length=200,blank=True)
    rec_file = models.FileField(upload_to='recordings')

forms.py

from django import forms 
from songstorage.models import Recording
class RecordingForm(forms.ModelForm):
    rec_file=forms.FileField(label='Upload File')
    rec_title=forms.CharField(label='Recording Title',required=False)       
    class Meta:
        model=Recording

views.py

def addrecordings(request,recordingfile):
    #if there is a recordingfile in the url, the user is editing...
    if recordingfile:
        recording=Recording.objects.get(rec_title=recordingfile)
        recording_form = RecordingForm(instance=recording)
    #...Otherwise a new form is createing a new one
    else:
        recording_form = RecordingForm(request.POST, request.FILES)

    #When the form is submitted, do the following:
    if request.method == 'POST': 
        #check if its valid
        if recording_form.is_valid():
            recording_form.save() 
            #if sucessfully submitted, redirect
            return redirect('/recordings/')
    return render_to_response('addrecordings.html','recording_form':recording_form,context_instance=RequestContext(request))

【问题讨论】:

遇到类似问题,请问您解决了吗? 我认为 Django 应该添加一个功能来解决这个问题。 【参考方案1】:

我遇到了同样的问题,无法弄清楚如何也无法搜索任何有用的东西,我目前的解决方案是在您的场景中使用另一种形式:

class RecordingUpdateForm(RecordingForm):
    rec_file=forms.FileField(label='Upload File', required=False)

唯一的区别是我使用的是基于 UpdateView 类的视图,所以你必须修改你的视图函数以使用RecordingUpdateForm 进行更新。

【讨论】:

【参考方案2】:

我遇到了同样的问题。

您可以覆盖模型的默认清理函数。这将验证所有表单,用户可以在编辑时更改图像文件,并且文件保证非空。

class MyModel(models.Model):
  image = models.ImageField(blank=True)
  def clean(self, *args, **kwargs):
    super(MyModel, self).clean(*args, **kwargs)
    if not self.image:
      raise ValidationError('Please provide an image')

【讨论】:

以上是关于使用文件字段编辑 Django 模型而不重新上传文件的主要内容,如果未能解决你的问题,请参考以下文章

django 快速实现文件上传

Django 多文件字段

Django:上传文件并读取其内容以填充模型?

Django:从服务器上的现有文件手动创建模型中的图像字段

仅在我重新加载 django 服务器后才提供上传的媒体文件

向 Django 添加文本区域的正确方法是啥?