0

I would like to save the file mime type by getting it on pre_save signal.

from django.db.models.signals import pre_save
from django.db import models
import magic

class Media (models.Media):
    file = models.FileField()
    content_type = models.CharField(max_length=128, editable=False)

def media_pre_save(sender, instance, *args, **kwargs):
    if not instance.content_type:
        mime = magic.Magic(mime=True)
        instance.content_type = mime.from_buffer(instance.file.read())
pre_save.connect(media_pre_save, sender=Media)

But I'm getting application/x-empty when I view it in db. What am I doing wrong?

  • Does this answer your question? [How does one use magic to verify file type in a Django form clean method?](https://stackoverflow.com/questions/8647401/how-does-one-use-magic-to-verify-file-type-in-a-django-form-clean-method) – Akshat Zala Apr 09 '20 at 06:52
  • Thanks, but that one gets the file from form object, is it possible to get it from instance? I would like to do the same thing but with the given parameters on `media_pre_save`. – Roger the Shrubber Apr 09 '20 at 07:04

1 Answers1

1

I finally figured out how to get the uploaded file absolute path and using the from_file method of magic like so:

instance.content_type = magic.from_file(instance.file.path, mime=True)

Updated answer:

I sometimes get empty file if file is a bit large so I have to "seek" from the beginning of the uploaded file and using the from_buffer method of magic like so:

instance.file.seek(0)
instance.content_type = magic.from_buffer(instance.file.read(), mime=True)

I owe the answer to the following links: Edit uploaded file (djangos FileField) using pre_save signal and https://github.com/ahupp/python-magic