Search code examples
javascriptpythondjangodjango-staticfilesdjango-settings

JavaScript not found in Django


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:

{% load static %}

<link rel="stylesheet" href="/static/css/style.css?{% now "U" %}"/>


<script type="module" src={% static "javascript/app.js" %}></script>

settings.py:

BASE_DIR = Path(__file__).resolve(strict=True).parent.parent

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'musicPlayer',
]

STATIC_URL = '/static/'


STATICFILES_DIRS = [
    BASE_DIR / "static",
    'musicPlayer/static/javascript/app.js',
]

Solution

  • You need to give a static directory to the STATICFILE_DIRS setting, not the full path:

    BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
    MUSIC_PLAYER_DIR = BASE_DIR / 'musicPlayer'
    
    STATICFILES_DIRS = [
        BASE_DIR / 'static',
        MUSIC_PLAYER_DIR / 'static',
    ]
    

    And in your template, you need to put double quotes around the static tag, and single quotes inside the tag:

    {% load static %}
    <link rel="stylesheet" href="{% static 'css/style.css' %}?{% now 'U' %}"/>
    
    <script type="text/javascript" src="{% static 'javascript/app.js' %}"></script>
    

    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"