Django音频文件表单验证

时间:2017-04-19 22:15:40

标签: python django forms validation audio

我正在尝试将文件验证添加到我的Django项目中。在我尝试添加一个将解析文件的python库之前,我想确保我可以检查文件大小,扩展名和内容类型。对于我在forms.py中的模型表单,我有:

class PostForm(forms.ModelForm):

def clean_audio_file(self, form):
    file = self.cleaned_data.get('sound')


    if file:
        if file._size > 4*1024*1024:
            raise ValidationError("Audio file too large ( > 4mb )")
        if not file.content-type in ["audio/mpeg","audio/wav"]:
            raise ValidationError("Content-Type is not mpeg")
        if not os.path.splitext(file.name)[1] in [".mp3",".wav"]:
            raise ValidationError("Doesn't have proper extension")

            return file
        else:
            raise ValidationError("Couldn't read uploaded file")

class Meta:
    model = Places
    fields = [

        'title',
        'longitude',
        'latitude',
        'sound',

    ]

对于我的观点,我有:

def post_create(request):
form= PostForm(request.POST or None, request.FILES or None)
form_class = PostForm()

if form.is_valid():     
    instance = form.save(commit=False)
    instance.save()
    messages.success(request, 'Successfully Created')
    return HttpResponseRedirect('/')


context= {
    'form': form,
}
return render(request, 'location/post_form.html',context)

我已经浏览了几次Docs,并查找了类似文件验证的示例,但由于某种原因,我上传的文件未经过验证。表单按预期工作,但它仍然允许文件太大和文件类型不正确而不会引发验证错误。关于我哪里出错的任何提示?

1 个答案:

答案 0 :(得分:1)

clean_audio_file()被叫到哪里?表单在验证时会自动调用clean_{field name}()clean(),但您的字段名称会改为sound。将其重命名为clean_sound()或仅clean(),因为您还没有。{/ p>

另外UploadedFile.size is a thing,不确定为什么要改为_size