Reputation: 1040
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
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
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