4

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

请用1个例子解释我。

模型.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)

表格.py

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

2 回答 2

4

您可以通过Form的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
于 2012-04-23T05:47:52.863 回答
2

这些链接可能会对您有所帮助:

仅接受 FileField 中的特定文件类型,服务器端

https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#uploadedfile-objects

于 2012-04-23T03:47:37.727 回答