Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
like image 260
Dmitrii Pisarenko Avatar asked Aug 04 '12 19:08

Dmitrii Pisarenko


2 Answers

I had an issue with Django serving javascript files as text/plain with the included server, which doesn't work too well with ES6 modules. I found out here that you could change file extension associations by placing the following lines in your settings.py:

#settings.py
if DEBUG:
    import mimetypes
    mimetypes.add_type("application/javascript", ".js", True)

and javascript files were now served as application/javascript.

like image 87
Alexandre Cox Avatar answered Sep 24 '22 01:09

Alexandre Cox


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.

like image 21
Daniel Roseman Avatar answered Sep 24 '22 01:09

Daniel Roseman