如何在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" ))
答案 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)