[Fixed]-Reading file data during form's clean method

30👍

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

FILE_UPLOAD_HANDLERS default:

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

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

Edit:

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'])}

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

Edit:

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))

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')

Leave a comment