Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Which file types does Django's image field support / not support by default?

I see all these posts which talk about 'how to limit Django's imagefield to only accept certain file types' but I am yet to find a list of all the file types which Django's imagefield supports / doesn't support by default.

Is there a list of file types which Django's imagefield supports / doesn't support by default? Or does Django's imagefield allow any filetype to be submitted?

(Will django allow users to upload .pdf, .psd, .doc etc. files in an imagefield or will it raise an error?)

like image 441
SilentDev Avatar asked Dec 14 '22 21:12

SilentDev


2 Answers

Year Of My Answer: 2020

I'm knee-deep in this same question myself and ran across some learnings I thought I'd share.

In django.core.validators lives a function named get_available_image_extensions(). Try this out.

from django.core import validators

validators.get_available_image_extensions()

Returns:

['blp', 'bmp', 'dib', 'bufr', 'cur', 'pcx', 'dcx', 'dds', 'ps', 'eps', 'fit',
 'fits', 'fli', 'flc', 'ftc', 'ftu', 'gbr', 'gif', 'grib', 'h5', 'hdf', 'png',
 'apng', 'jp2', 'j2k', 'jpc', 'jpf', 'jpx', 'j2c', 'icns', 'ico', 'im', 'iim',
 'tif', 'tiff', 'jfif', 'jpe', 'jpg', 'jpeg', 'mpg', 'mpeg', 'mpo', 'msp',
 'palm', 'pcd', 'pdf', 'pxr', 'pbm', 'pgm', 'ppm', 'pnm', 'psd', 'bw', 'rgb',
 'rgba', 'sgi', 'ras', 'tga', 'icb', 'vda', 'vst', 'webp', 'wmf', 'emf', 'xbm',
 'xpm']

The function itself tries to use PIL. Here it is in all its glory:

def get_available_image_extensions():
    try:
        from PIL import Image
    except ImportError:
        return []
    else:
        Image.init()
        return [ext.lower()[1:] for ext in Image.EXTENSION]

Related function validate_image_file_extension(value) uses get_available_image_extensions() to determine the allowed_extensions keyword argument.

Here that function is:

def validate_image_file_extension(value):
    return FileExtensionValidator(allowed_extensions=get_available_image_extensions())(value)

Hopefully this answers the question of:

Is there a list of file types which Django's imagefield supports / doesn't support by default?

like image 193
Jarad Avatar answered Mar 30 '23 01:03

Jarad


Django's ImageField requires the third-party package Pillow (or PIL, but support is deprecated). It depends on these packages to verify that a file is indeed an image. This is not dependant on the file extension, but on the content of the file itself.

If you want to know if a certain type of file is supported, you should find out which version of Pillow/PIL you are using, and check the corresponding documentation.

like image 22
knbk Avatar answered Mar 29 '23 23:03

knbk