django content_type of a image while testing

352 Views Asked by At

I want to get the content type of the image and I am doing

image = open(PATH_TO_IMAGE)

print(image.name.content_type)

It gives me error saying str object has no attribute content_type

How can I get the content type?

I am doing this in a test and in my view I am getting content_type of image. I can pass the image to the view but its not giving me content typ

2

There are 2 best solutions below

0
On

Haven't tested this but from what I remember you can use the built in imghdr module and use print(imghdr.what(image)) to get the image's format type

2
On

You can use Magic library to guess the type of any file.

import magic
image_type = magic.from_buffer(image.read(), mime = True)

Or

You can use Imghdr as suggested in other answers.