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 :)
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With