在表单的清洁方法中读取文件数据 [英] Reading file data during form's clean method

查看:198
本文介绍了在表单的清洁方法中读取文件数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在努力实施我以前的问题

So, I'm working on implementing the answer to 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 在磁盘上需要类似文件的对象或文件名(I 认为) - 第一种情况(上传的文件大于内存中处理的文件的大小)工作正常,但是我不知道如何处理 InMemoryUploadedFile ,否则的话。我试过:

Mutagen needs file-like objects or filenames on disk (I think) - the first case (where the uploaded file is larger than the size of file handled in memory) works fine, but I don't know how to handle InMemoryUploadedFile that I get otherwise. I've tried:

# 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有什么问题,还是我做错了?

Is there something wrong with mutagen, or am I doing it wrong?

在我的<$ c中修改 FILE_UPLOAD_HANDLERS 设置$ c> ModelAdmin 类如下:

Modifying the FILE_UPLOAD_HANDLERS setting on the fly in my ModelAdmin class like this:

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 whe n我提交:

Gets me the following error 500 when I hit submit:


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

You cannot set the upload handlers after the upload has been processed.

即使我尽早做到这一点我可以!

even though I'm doing it as early as I possibly can!

另外,我不知道我我已经得到一个保存方法(我已经看过 dir(self.files ['mp3'])。文件) dir(self.files ['mp3']))。

Also, I'm not sure I've got a save method on the object I'm getting back (I've looked in dir(self.files['mp3'].file) and dir(self.files['mp3'])).

推荐答案

您可以尝试更改您的 FILE_UPLOAD_HANDLERS ,所以Django总是使用临时文件处理程序:

You could try to change your FILE_UPLOAD_HANDLERS in such a way so Django always uses temporay file handler:

FILE_UPLOAD_HANDLERS 默认值:

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

所以你可以只留下 TemporaryFi leuploadHandler 通过覆盖您的settings.py中的设置。

So you could leave only TemporaryFileUploadHandler by overriding the setting in your settings.py.

编辑:

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

Much simpler, should have thought of it at the first place :(:

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

You can save InMemoryUploadedFile to the disk this way and then use the path to that file to work with mutagen.

编辑:

没有模型实例的相同的东西。
$ b

Same thing without a models instance.

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中,当我尝试保存其他任何地方我得到 Suspicio我们操作,因为你可以写的地方有限制...你应该在检查之后删除这个文件,我猜,真正的东西将在你的模型上。

Note that it's saving the file in MEDIA_ROOT, when i try to save it anywhere else i get SuspiciousOperation since there are limits to where you can write... You should delete this file after examining it i guess, the real thing will be on your model...

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

这篇关于在表单的清洁方法中读取文件数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆