Search code examples
javascriptdjangomime-types

How to set content type of JavaScript files in Django


I have a Django application, which requires several JavaScript files.

In Chrome I get the error "Resource interpreted as Script, but transferred with MIME type text/html".

enter image description here

AFAIK (see 2) in order to fix this problem, I need to configure Django so that JavaScript files are returned with content-type "application/x-javascript".

How can I do this in Django?

UPDATE: I followed the advice by Daniel Roseman and found following solution.

1) Modify urls.py:

urlpatterns = patterns('',
    ...
    url(r'.*\.js$', java_script),
    ...
)

2) Add following function to views.py:

def java_script(request):
    filename = request.path.strip("/")
    data = open(filename, "rb").read()
    return HttpResponse(data, mimetype="application/x-javascript")

Solution

  • I suspect the problem is not what you think it is. What is probably actually happening is that your JS files are not being served at all: instead, the Django error page is being sent. You need to figure out why.