Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Get uploaded file type / mimetype

Tags:

Is there a way to get the content type of an upload file when overwriting the models save method? I have tried this:

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

But it did not work. In this example, self.file is a model.FileField:

file = models.FileField(upload_to='uploads/%m-%Y/') 

Edit: I want to be able to save the content type to the database, so I'll need it before the save is actually complete :)

like image 505
Hanpan Avatar asked Jan 31 '11 16:01

Hanpan


People also ask

What is MIME type in Django?

The Django development server uses the mimetypes module to guess the appropriate MIME type for any given file, and under the hood that module uses different configurations depending on your OS.


1 Answers

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 

settings.py

TASK_UPLOAD_FILE_TYPES = ['pdf', 'vnd.oasis.opendocument.text','vnd.ms-excel','msword','application',] TASK_UPLOAD_FILE_MAX_SIZE = "5242880" 
like image 147
moskrc Avatar answered Sep 29 '22 11:09

moskrc