Django prevent image upload containing possible XSS code

Why not just verify that the file is a valid image?:

from PIL import Image
image = Image.open(file)
image.verify()

As another poster has suggested, you can indeed attempt a transformation and check if an exception is thrown, but verify() will probably be quicker.

Or maybe you can try detecting the type?:

import imghdr
path = 'Image.jpg'
imghdr.what(path)

Or

from PIL import Image
image = Image.open('myimage.png')
image.format

Using any of the above methods, you can determine if the file is actually an image or not. If it is not an image, then consider the file as spurious, and do not output it on any of your web pages. By not outputting the file, there is no risk of XSS from this vector, because even if the file is HTML, by not outputting it on your page, it cannot compromise your page.