Search code examples
javascriptpythondjangodjango-templatesdjango-staticfiles

How to include JavaScript in Django Templates?


I'm working on a project and following the documentation. I didn't succeed to include javascript.

Here is my settings:

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

STATIC_ROOT = '/static/'

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)

So, I have created a static folder with a javascipt file in my project.

myproject/static/app.js

my urls.py:

urlpatterns = [
    url(r'^$', 'app.views.home'),
    url(r'^admin/', include(admin.site.urls)),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

and in my template: myproject/templates/base.html:

<!DOCTYPE html>
<head>
  {% load static %}
  <script src="{% static 'app.js' %}"></script>   
  <title>Site</title>
</head>
<body>
<img src="{% static 'img.png' %}" alt="Mon image" />
  {% block content %}{% endblock %}
</body>
</html>

My other template:

{% block content %}
    hello world
{% endblock %}

I have the "hello world" on

http://127.0.0.1:8000/

but i do not have my image or script.

I tried so many different things but I never succeed


Solution

  • urls.py

    from django.conf.urls import include, url
    from django.contrib import admin
    
    urlpatterns = [
        url(r'^admin/', include(admin.site.urls)),
    ]
    

    settings.py

    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, "static"),
    )
    
    STATIC_URL = '/static/'
    
    # remove STATIC_ROOT
    

    base.html

    Your title tag was not closed.

    <!DOCTYPE html>
    <head>
      {% load static %}
      <script src="{% static 'app.js' %}"></script>   
      <title>Site</title>
    </head>
    <body>
    <img src="{% static 'img.png' %}" alt="Mon image" />
      {% block content %}{% endblock %}
    </body>
    </html>