在保存对象之前处理文件上传 [英] Processing file uploads before object is saved
问题描述
我有一个这样的模型:
class Talk(BaseModel):
title = models.CharField(max_length=200)
mp3 = models.FileField(upload_to = u'talks/', max_length=200)
seconds = models.IntegerField(blank = True, null = True)
我要在保存上传的文件是MP3之前验证,如下所示:
I want to validate before saving that the uploaded file is an MP3, like this:
def is_mp3(path_to_file):
from mutagen.mp3 import MP3
audio = MP3(path_to_file)
return not audio.info.sketchy
一旦我确定我有一个MP3,我想保存长度在秒属性中的谈话,像这样:
Once I'm sure I've got an MP3, I want to save the length of the talk in the seconds attribute, like this:
audio = MP3(path_to_file)
self.seconds = audio.info.length
问题是,在保存之前,上传的文件没有路径请参阅此门票,关闭为 wontfix
),所以我无法处理MP3。
The problem is, before saving, the uploaded file doesn't have a path (see this ticket, closed as wontfix
), so I can't process the MP3.
我想提出一个很好的验证错误,以便 ModelForm
可以显示一个有用的错误(你傻子,你没有上传MP3或某事)。
I'd like to raise a nice validation error so that ModelForm
s can display a helpful error ("You idiot, you didn't upload an MP3" or something).
任何想法我可以在保存文件之前访问该文件吗?
Any idea how I can go about accessing the file before it's saved?
ps如果有人知道更好的验证文件的方式是MP3,我都是耳朵 - 我也想要弄清ID3的数据(设置艺术家,专辑,标题和可能的专辑封面,所以我需要它可以处理诱变剂)。
推荐答案
您可以访问 request.FILES ,而在您的视图中。
You can access the file data in request.FILES while in your view.
我认为最好的方法是将上传的文件绑定到表单,覆盖表单 clean method ,获取 UploadedFile对象从clean_data,验证它,无论如何你喜欢,然后覆盖保存方法,并使用有关该文件的信息填充您的模型实例,然后保存。
I think that best way is to bind uploaded files to a form, override the forms clean method, get the UploadedFile object from cleaned_data, validate it anyway you like, then override the save method and populate your models instance with information about the file and then save it.
这篇关于在保存对象之前处理文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!