将文件上传限制为仅限音频和视频格式

时间:2012-04-23 03:40:36

标签: django django-templates

如何在Django中添加只接受特定文件的音频和视频文件字段?

请举一个例子解释我。

models.py

class Post(models.Model):
     audio_file = models.FileField(upload_to = u'mp3/', max_length=200)
     video_file = models.FileField(upload_to = u'video/', max_length=200)

forms.py

class PostForm(forms.Form):
     audio_file = forms.FileField( label = _(u"Audio File" ))
     video_file = forms.FileField( label = _(u"Video File" ))

2 个答案:

答案 0 :(得分:4)

您只需通过表格clean方法

进行检查即可
class FileUploadForm( forms.Form ):
    audio_file = forms.FileField( label = _(u"Audio File" ))
    ...

def clean( self ): 
    cleaned_data = self.cleaned_data
    file = cleaned_data.get( "audio_file" )
    file_exts = ('.mp3', ) 

    if file is None:

        raise forms.ValidationError( 'Please select file first ' ) 

    if not file.content_type in settings.UPLOAD_AUDIO_TYPE: #UPLOAD_AUDIO_TYPE contains mime types of required file

        raise forms.ValidationError( 'Audio accepted only in: %s' % ' '.join( file_exts ) ) 


    return cleaned_data

答案 1 :(得分:2)