How to include JavaScript in Django Templates?
Asked Answered
R

6

31

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

Roomette answered 18/5, 2015 at 21:45 Comment(2)
Before using the 'static' tag, try to get the file using the full url (e.g. /static/myproject/img.png). That way you can find out where your files are located by Django (it can get a bit tricky sometimes).Fulltime
Django docs provide a guide on how to include static files like JS docs.djangoproject.com/en/3.2/howto/static-filesMira
C
58

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>
Crenation answered 18/5, 2015 at 21:49 Comment(3)
It didn't work. I still got no javascript file includeRoomette
Set STATICFILES_DIRS = () and STATIC_ROOT = os.path.join(BASE_DIR, 'static')Crenation
Let us continue this discussion in chat.Crenation
T
4

Your template should say {% load staticfiles %} instead of {% load static %}

Source: https://docs.djangoproject.com/en/1.8/howto/static-files/

Also, os.path.join(BASE_DIR, "static"), only looks for static files in your apps, as in app/static/app/static.js. If you have static files that do not belong to any specific app, but rather to the project, you need to add the folder explicitly. See point 4 of 'Configuring static files' on the docs page I mentioned.

Tailpipe answered 18/5, 2015 at 22:18 Comment(1)
I followed the doc first but it didn't work. I try with load static and load staticfiles but it didn't workRoomette
F
2

From my understanding, the STATICFILES_DIRS should be in the settings.py and defined like this:

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

Please check the documentation.

Fiji answered 28/5, 2020 at 15:10 Comment(0)
D
1

Create directory named 'static' at base directory. i.e. at similar level to project directory. Then add following in settings.py

STATIC_URL = '/static/'
#setting for static files
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) code here
Distaste answered 29/11, 2021 at 17:48 Comment(0)
A
0

I am new at programing thus take my points with a pinch of salt. There i go. maybe you have more apps meaning you gotta check your tree as it should go as the django documentations points. meaning that you should have your_app/static/your_app/in here you must put three more folders corresponding to css, images and js all with their respective files.

Also notice that your static url should be named diferent than your static root. Once you have done this you must tell django where to find the statics for each app thus you gotta state it within the STATICFILES_DIRS.

After all this then you gotta run the collectstatic command.

I´m still missing the part in which you connect the js files of each app to the template.. so I cannot further help you dude.... hope it helps a little bit

Adigranth answered 24/5, 2020 at 16:34 Comment(0)
O
0

You can include CSS and JavaScript in Django Templates. *My answer explains how to include JavaScript in Django Admin.

For example, there are static/my_app1/css/hello.css, static/my_app1/js/hello.js and templates/index.html as shown below:

django-project
 |-core
 |  └-settings.py
 |-my_app1
 |-my_app2
 |-static
 |  └-my_app1
 |     |-css
 |     |  └-hello.css # Here
 |     └-js
 |        └-hello.js # Here
 |
 └-templates
    └-index.html # Here

Then, set BASE_DIR / 'templates' to DIRS in TEMPLATES and set BASE_DIR / 'static/' to STATICFILES_DIRS in settings.py as shown below so that Django can recognize templates and static folders just under django-project. *My answer explains how to set Django Templates and I recommand to set whitenoise following my answer to disable your browser to cache the static files of Django:

# "settings.py"

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            BASE_DIR / 'templates' # Here
        ],
        ...
    },
]

...

STATIC_URL = 'static/'
STATIC_ROOT = 'staticfiles/'
STATICFILES_DIRS = [
    BASE_DIR / 'static/' # Here
]

Lastly, add <link rel="stylesheet" ...> and <script ...></script> to index.html as shown below:

{# "index.html" #}

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="{% static 'my_app1/css/hello.css' %}">
</head>
<body>
    <script src="{% static 'my_app1/js/hello.js' %}"></script>
</body>
</html>
Oto answered 26/8, 2023 at 16:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.