1

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?

2
  • first, you are writing and HTML tag <script> in the onClick attribute Commented Mar 2, 2018 at 19:23
  • Please refere this link. Commented Jan 11, 2021 at 14:46

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

8 Comments

Sadly it still doesn't work. Should ` <script src="{% static 'pizzas/hack.js' %}"></script>` be included in the template file?
yes it should be in your HTML, maybe it not working cause of your Django settings, you need to set STATIC_URL and STATICFILES_DIRS to your static files folder
STATIC_URL is set OK. I don't think I need STATICFILES_DIRS in this case, because according to the Django documentation it is used only when I want to use static files that are not tied to a particular app?
@barciewicz I edited my answer hopefully that's your issue
Django's 2.0 documentation actually says {% load static %}: docs.djangoproject.com/en/2.0/howto/static-files
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.