Home > Back-end >  How to link JavaScript page to django web app?
How to link JavaScript page to django web app?

Time:06-23

So I have a javascript file I'm trying to link to my html file. I've managed to connect css files to multiple html files so it seems like my static settings and such are working well however I get an error message : "Not Found: /item-store.js" (item-store.js is my JavaScript file). (BTW : My html file is named "item-store.html) I'm not sure how to fix the issue. Any ideas?

Here is my html file :

{% load static %}

<!DOCTYPE html>
<html lang="en">
  <head>
    ...Code...
  </head>
  <body>
    ...Code...
    <script src="item-store.js"></script>
  </body>
</html>

A few lines of my settings.py file :

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app'
]
TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [BASE_DIR/'templates'],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},
]
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "templates"),
)
MEDIA_ROOT = ''
MEDIA_URL = ''

I'll be active today every once in a while so i'll be able to clarify anything if needed or provide more information. Thank you for your time!

CodePudding user response:

Here is the pattern:

template.html

<srcipt src="{% static 'folder/script.js' %}"></script>

settings.py

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'staticfiles')
]

project structure:

project
|- app1
|- app2
|- ...
|- project
|- staticfiles
  |- folder
    |- script.js
|- templates
|- manage.py
|- ...
  • Related