Reading file data during form's clean method

Posted by Dominic Rodger on Stack Overflow See other posts from Stack Overflow or by Dominic Rodger
Published on 2010-05-10T21:30:13Z Indexed on 2010/05/10 21:34 UTC
Read the original article Hit count: 188

So, I'm working on implementing the answer to my previous question.

Here's my model:

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

Here's my form:

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 needs file-like objects - 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
audio = MP3(self.files['mp3'].file.read())

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

© Stack Overflow or respective owner

Related posts about django

Related posts about django-file-upload