Search code examples
pythondjangodjango-rest-frameworkmime-typesdjango-serializer

How to get MIME type of FileField in DRF and send to parameters?


I want to send mime type of the FileField in drf. But I don't know how to.

{

    "id": 1,
    "document": "http://127.0.0.1:8000/images/articles_auth_with_user_eZUJmTW.png",
    "filesize": "239.55 KB",
    "filename": "articles_auth_with_user_eZUJmTW.png"
    "mimetype": ""



},

This is response I am sending. I want to send mime type here.

Models.py:

class DocumentModel(models.Model):
    id=models.AutoField(primary_key=True, auto_created=True, verbose_name="DOCUMENT_ID")
    document=models.FileField()
    

    class Meta:
        verbose_name_plural="Documents"
        ordering=["document"]

    def __str__(self):
        return f'{self.document}'

    @property
    def filesize(self):
        x = self.document.size
        y = 512000
        if x < y:
            value = round(x / 1024, 2)
            ext = ' KB'
        elif x < y * 1024:
            value = round(x / (1024 * 1024), 2)
            ext = ' MB'
        else:
            value = round(x / (1024 * 1024 * 1024), 2)
            ext = ' GB'
        return str(value) + ext

    @property
    def filename(self):
        return self.document.name

Serializers.py:

class DocumentSerializer(serializers.ModelSerializer):

    
   
   

    class Meta:
        model=DocumentModel
        fields = ['id', 'document', 'filesize', 'filename']

Solution

  • Ok i solved and finally got the mime type of any file when it get uploaded to print it on frontend by using mimetypes library

      @property
        def mimetype(self):
            return mimetypes.guess_type(self.document.url)[0]