Amit Pathak
Amit Pathak

Reputation: 1367

How to mention static files in .js file for a django project?

I am facing an issue for mentioning one of the files in my django project for a .js file

One of the lines in main.js reads

navigator.serviceWorker.register("{% static '/static/sw.js' %}")

but while running the project it says Not Found: /sw.js

This is the directory structure -

enter image description here

How should I mention the sw.js file in my main.js file to avoid fileNotFound error?

Added to settings.py -

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

urls.py includes

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
    path('/push_v1/', push_v1),
    path('/subscription/', subscription),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Complete error - enter image description here

Find the code on Github for reference Code Link

Upvotes: 2

Views: 1700

Answers (1)

ngawang13
ngawang13

Reputation: 673

in your setting.py file set the location for your static files

STATIC_URL = '/static/'

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

and than in you template first load the static and than set the script file n template itself.

{% load static %}

<script type="text/javascript" src="{% static 'sw.js' %}"></script>

Upvotes: 1

Related Questions