Get Django to return and execute javascript

不问归期 提交于 2019-12-04 19:33:06


So I'm working with django and file uploads and I need a javascript function to execute after the file has been uploaded. I have a file upload handler in my which looks like this:

def upload_file(request):   
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():        
        for f in request.FILES.getlist('fileAttachments'):     
        return HttpJavascriptResponse('parent.Response_OK();')
        return HttpResponse("Failed to upload attachment.")

And I found a django snippet from and I put the HttpJavascriptResponse class in my code. It looks as follows:

class HttpJavascriptResponse(HttpResponse):
    def __init__(self,content):

However, when I upload a file the browser simple renders "parent.Response_OK();" on the screen instead of actually executing the javascript. And Chrome gives me the warning: "Resource interpreted as Document but transferred with MIME type text/javascript"

Is there anyway to get to execute the script?


I believe this will work.

return HttpResponse("<script>parent.Response_OK();</script>")

However, you might think about returning a success (200) status code in this case, and then having some javascript in parent attach to the load event of this child, and branch based on return status code. That way you have a separation of view rendering code and view behavior code.


A better way is to pass the mime to the HttpResponse Object.

return HttpResponse("parent.Response_OK()", mimetype="application/x-javascript")


Chase's solution worked for me, though I need to execute more javascript than I care to put in a python string:

from django.http import HttpResponse
from django.contrib.staticfiles.templatetags import staticfiles

    return HttpResponse("<script src='{src}'></script>".format(
        src = staticfiles.static('/path/to/something.js')))


I ended up here looking for a way to serve a dynamic js file using django.

Here is my solution :

return render(request, 'myscript.js', {'foo':'bar'},