在表单的清理方法中读取文件数据

时间:2010-05-10 21:30:14

标签: django django-file-upload mutagen

所以,我正在努力实现my previous question的答案。

这是我的模特:

class Talk(models.Model):
  title        = models.CharField(max_length=200)
  mp3          = models.FileField(upload_to = u'talks/', max_length=200)

这是我的表格:

class TalkForm(forms.ModelForm):
  def clean(self):
    super(TalkForm, self).clean()
    cleaned_data = self.cleaned_data

    if u'mp3' in self.files:
      from mutagen.mp3 import MP3
      if hasattr(self.files['mp3'], 'temporary_file_path'):
        audio = MP3(self.files['mp3'].temporary_file_path())
      else:
        # What goes here?
        audio = None # setting to None for now
      ...
    return cleaned_data

  class Meta:
    model = Talk

Mutagen需要磁盘上类似文件的对象或文件名(我) - 第一种情况(上传的文件大于内存中处理的文件大小)工作正常,但我不知道如何处理我得到的InMemoryUploadedFile。我试过了:

# TypeError (coercing to Unicode: need string or buffer, InMemoryUploadedFile found)
audio = MP3(self.files['mp3'])

# TypeError (coercing to Unicode: need string or buffer, cStringIO.StringO found)
audio = MP3(self.files['mp3'].file)

# Hangs seemingly indefinitely on my test file (~800KB)
audio = MP3(self.files['mp3'].file.read())

mutagen有什么问题,或者我做错了吗?

在rebus'回答

之后

在我的FILE_UPLOAD_HANDLERS课程中动态修改ModelAdmin设置,如下所示:

def add_view(self, request, form_url='', extra_context=None):
  request.upload_handlers = [TemporaryFileUploadHandler()]
  return super(TalkAdmin, self).add_view(request, form_url, extra_context)

点击提交时收到以下错误500:

  

处理完上传后,您无法设置上传处理程序。

尽管我尽可能早地做到了!

另外,我不确定我在回复的对象上有save方法(我查看了dir(self.files['mp3'].file)dir(self.files['mp3']))。

1 个答案:

答案 0 :(得分:23)

您可以尝试以这种方式更改FILE_UPLOAD_HANDLERS,以便Django始终使用临时文件处理程序:

FILE_UPLOAD_HANDLERS默认:

("django.core.files.uploadhandler.MemoryFileUploadHandler",
 "django.core.files.uploadhandler.TemporaryFileUploadHandler",)

因此,您只能通过覆盖settings.py中的设置来留下TemporaryFileUploadHandler

修改

更简单,首先应该想到它:(:

from your.models import Talk
mp3 = self.files['mp3']
f = Talk.mp3.save('somename.mp3', mp3)
MP3(f.mp3.path)
>>> {'TRCK': TRCK(encoding=0, text=[u'5'])}

您可以通过这种方式将InMemoryUploadedFile保存到磁盘,然后使用该文件的路径来使用mutagen

修改

没有模型实例也是如此。

import os

from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.conf import settings

from mutagen.mp3 import MP3

mp3 = request.FILES['mp3'] # or self.files['mp3'] in your form

path = default_storage.save('tmp/somename.mp3', ContentFile(mp3.read()))
MP3(os.path.join(settings.MEDIA_ROOT, path))

请注意,它将文件保存在MEDIA_ROOT中,当我尝试将其保存在其他任何地方时我得到SuspiciousOperation,因为您可以写入的位置有限制...您应该在检查后删除此文件我猜,真实的东西将在你的模型上......

path = default_storage.delete('tmp/somename.mp3')