admin管理员组

文章数量:1314255

In my Django project 'pizzeria', I have created a static files folder for the app 'pizzas', so the folder structure is: pizzeria/pizzas/static/pizzas/. Inside this folder I have a JavaScript 'hack.js':

//hack.js
<script>   
document.getElementById("home page").innerHTML="Hacked!"
</script>

Now I want to include this script in my Django template (pizzeria/pizzas/templates/pizzas/base.html), however the following setup does not work (the innerHTML does not change on button click):

{% load static %}

<p>
<a href="{% url 'pizzas:index' %}" id="home page">Home page</a>
<a href="{% url 'pizzas:pizzas' %}">Our pizzas</a>
<button onclick="{% static 'pizzas/hack.js' %}">Hack!</button>
</p>

{% block content %} {% endblock content %}

What am I doing wrong?

In my Django project 'pizzeria', I have created a static files folder for the app 'pizzas', so the folder structure is: pizzeria/pizzas/static/pizzas/. Inside this folder I have a JavaScript 'hack.js':

//hack.js
<script>   
document.getElementById("home page").innerHTML="Hacked!"
</script>

Now I want to include this script in my Django template (pizzeria/pizzas/templates/pizzas/base.html), however the following setup does not work (the innerHTML does not change on button click):

{% load static %}

<p>
<a href="{% url 'pizzas:index' %}" id="home page">Home page</a>
<a href="{% url 'pizzas:pizzas' %}">Our pizzas</a>
<button onclick="{% static 'pizzas/hack.js' %}">Hack!</button>
</p>

{% block content %} {% endblock content %}

What am I doing wrong?

Share Improve this question edited Mar 2, 2018 at 19:33 Jason Aller 3,65228 gold badges41 silver badges39 bronze badges asked Mar 2, 2018 at 19:21 barciewiczbarciewicz 3,8236 gold badges34 silver badges86 bronze badges 2
  • first, you are writing and HTML tag <script> in the onClick attribute – h1b9b Commented Mar 2, 2018 at 19:23
  • Please refere this link. – Vinoth Commented Jan 11, 2021 at 14:46
Add a ment  | 

1 Answer 1

Reset to default 5

You should remove the script tag from your js file and include it with

  <script src="{% static 'pizzas/hack.js' %}"></script> 

With a hack.js file like

function onClick() {
   document.getElementById("home_page").innerHTML="Hacked!"
}

Tag ids shouldn't contain spaces, doc
Your button should be

<button onclick="onClick">Hack!</button>

本文标签: pythonHow to include JavaScript in a Django templateStack Overflow