gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:34:48 24 4
gpt4 key购买 nike

如何在仅接受特定文件的 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)

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

最佳答案

您可以简单地通过表单的 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

关于django - 将文件上传限制为仅音频和视频格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10274531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com