I am trying to use JavaScript within my Django project. I have made a static folder within my app containing css and js folders, and whilst my css is working my js files are not. Any help would be great, thanks.
HTML:
JavaScript
x
7
1
{% load static %}
2
3
<link rel="stylesheet" href="/static/css/style.css?{% now "U" %}"/>
4
5
6
<script type="module" src={% static "javascript/app.js" %}></script>
7
settings.py:
JavaScript
1
20
20
1
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
2
3
INSTALLED_APPS = [
4
'django.contrib.admin',
5
'django.contrib.auth',
6
'django.contrib.contenttypes',
7
'django.contrib.sessions',
8
'django.contrib.messages',
9
'django.contrib.staticfiles',
10
'musicPlayer',
11
]
12
13
STATIC_URL = '/static/'
14
15
16
STATICFILES_DIRS = [
17
BASE_DIR / "static",
18
'musicPlayer/static/javascript/app.js',
19
]
20
Advertisement
Answer
You need to give a static directory to the STATICFILE_DIRS
setting, not the full path:
JavaScript
1
8
1
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
2
MUSIC_PLAYER_DIR = BASE_DIR / 'musicPlayer'
3
4
STATICFILES_DIRS = [
5
BASE_DIR / 'static',
6
MUSIC_PLAYER_DIR / 'static',
7
]
8
And in your template, you need to put double quotes around the static
tag, and single quotes inside the tag:
JavaScript
1
5
1
{% load static %}
2
<link rel="stylesheet" href="{% static 'css/style.css' %}?{% now 'U' %}"/>
3
4
<script type="text/javascript" src="{% static 'javascript/app.js' %}"></script>
5
On a side note, I have never seen type="module"
on a script tag before, so I’m not sure if that will work. Generally its type="text/javascript"