[Fixed]-Django development server and MIME types


Turns out it was as simple as adding

    import mimetypes
    mimetypes.add_type("image/png", ".png", True)

to settings.py


The Django development server uses the mimetypes module to guess the appropriate MIME type for any given file, and under the hood that module uses different configurations depending on your OS.

On Windows in particular it loads content types from HKEY_CLASSES_ROOT in the registry (for instance the key HKEY_CLASSES_ROOT\.js\Content Type for .js files) and it seems this configuration can often be set in ways you wouldn’t expect (such as by opening a javascript file in a text editor)- it’s not even Python or Django specific, since Go also uses the registry and is affected the same way.

Modifying the registry key for the affected file extensions should fix this issue without requiring any Django settings changes (however it is a system-wide configuration change that may not be desirable):

Windows Registry Editor Version 5.00

; Fixing the question's issue with PNG
"Content Type"="image/png"

; Fixing a common problem with Javascript files
"Content Type"="text/javascript"

On other operating systems MIME mappings are configured in a file that most users will never modify, so this tends not to be a problem. If needed however, mimetypes.knownfiles is a list of paths expected to contain MIME type mappings which could be edited as needed.



Year 2020 ANSWER:

if you want any mime content type to auto detect by browser this is the solution.

after many painful failed static attempts this is the dynamic solution.

def fetch(request):
    import mimetypes
    try: return HttpResponse(fread(clientRequestUrl), content_type=mimetypes.guess_type(request.path)[0])
    except Exception as e: return HttpResponse(str(e)+'===> Error Thrown <br>')
  • here fread() reads file directly in try except block its just an I/O wrapper
  • content_type=mimetypes.guess_type(request.path)[0] does the MIME detection magic [0] ie first element is required because it returns a tuple first being the mime type and second being encoding.
  • request.path is passed in above line because it guesses MIME based on file path. for example text/css for file named stylsheet.css if client(browser) request it.
  • clientRequestUrl = exact url the client is trying to request to server.

Leave a comment