user2104778
user2104778

Reputation: 1040

Insert script to run on serving a template page with django

I know there is a simple answer to this but I haven't found it. In my views.py, I have a function that aims to add a javascript onload function to run when the page loads. The page loads with the script but the script doesn't run. See below:

from django.template.response import TemplateResponse
t = TemplateResponse(request, 'viewer/index.html', {})
t.render()
t.content = t.content + "<script type='text/javascript'>window.onload=function(){alert('here');}" + "</script>"
return t

Upvotes: 0

Views: 4658

Answers (2)

Thibault J
Thibault J

Reputation: 4446

Why not simply adding the script in your template? Or even better, in a dedicated javascript file? Django views are not the better plate to generate scripts, it will make your code error prone and harder to read and debug.

If you need to pass variables from python to your js, you can use something like that:

from django.template.response import TemplateResponse
context = {
    'variable': value,
}
t = TemplateResponse(request, 'viewer/index.html', context)

And in your template:

<html>
<head></head>
<body>
…
var config = {
    'variable': {{ variable }}
}
<script type="text/javascript" src="path/to/script.js"></script>
</body>

Upvotes: 3

Paul Draper
Paul Draper

Reputation: 83323

You should not be manipulating the TemplateResponse like that. Instead, pass the content in properly.

from django.template.response import TemplateResponse

script = "window.onload = function(){ alert('here'); }"
t = TemplateResponse(request, 'viewer/index.html', {
    "script": script
})
t.render()
return t

Then in your template

<html>
    <body>
        <script>{{ script }}</script>
    </body>
</html>

Upvotes: 1

Related Questions