【问题标题】:Restrict file upload to only audio and video formats将文件上传限制为仅音频和视频格式
【发布时间】:2012-05-03 17:01:56
【问题描述】:

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

请用 1 个例子解释一下。

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" ))

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    您可以通过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
    

    【讨论】:

      【解决方案2】:
      猜你喜欢
      • 2016-08-22
      • 2014-04-26
      • 1970-01-01
      • 2014-12-25
      • 2019-03-25
      • 2012-11-06
      • 2015-06-05
      • 2018-02-19
      • 1970-01-01
      相关资源
      最近更新 更多