gpt4 book ai didi

Django - 获取上传的文件类型/mimetype

转载 作者:行者123 更新时间:2023-12-03 14:38:18 27 4
gpt4 key购买 nike

覆盖模型保存方法时,有没有办法获取上传文件的内容类型?我试过这个:

def save(self):
print(self.file.content_type)
super(Media, self).save()

但它没有用。在这个例子中,self.file 是一个 model.FileField:
file = models.FileField(upload_to='uploads/%m-%Y/')

编辑:我希望能够将内容类型保存到数据库中,所以在保存实际完成之前我需要它:)

最佳答案

class MyForm(forms.ModelForm):

def clean_file(self):
file = self.cleaned_data['file']
try:
if file:
file_type = file.content_type.split('/')[0]
print file_type

if len(file.name.split('.')) == 1:
raise forms.ValidationError(_('File type is not supported'))

if file_type in settings.TASK_UPLOAD_FILE_TYPES:
if file._size > settings.TASK_UPLOAD_FILE_MAX_SIZE:
raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(settings.TASK_UPLOAD_FILE_MAX_SIZE), filesizeformat(file._size)))
else:
raise forms.ValidationError(_('File type is not supported'))
except:
pass

return file

设置.py
TASK_UPLOAD_FILE_TYPES = ['pdf', 'vnd.oasis.opendocument.text','vnd.ms-excel','msword','application',]
TASK_UPLOAD_FILE_MAX_SIZE = "5242880"

关于Django - 获取上传的文件类型/mimetype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4853581/

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