Home > Enterprise >  Django loads static CSS files but won't load JS files
Django loads static CSS files but won't load JS files

Time:02-03

I have been struggling with this for a couple of hours now. I have tried every option I could find so far on SO, but couldn't find any solution to my problem.

For some reason Django (version 4.1.6 in VS code) will load the css files, but not the javascript file. The css styling works, is adjustable (I can make changes to the css file and the website-style changes) and is visible in inspect element -> sources.

snippet of sources

The js file that I have made however is not. The script it's suppose to run on a button click, and works when the js script is placed within the html itself, but returns undefined when used as an external js file.

I have tried collectstatic, STATICFILES_DIRS, clearing my cache, moving the js file to different folders, used every different path I could think of (blog/js or static/blog/js or static/js or js for example in my script src) and even reinstalled django. When I use findstatic the js file is found.

I have simplified the example as much as possible below.

Settings.py

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

Views.py

class Archive(generic.ListView):
    queryset = Blog.objects.order_by('-pub_date')
    template_name = 'blog/archive.html'

Urls.py

urlpatterns = [
    path('', include('blog.urls')),
    path('admin/', admin.site.urls),

]

if settings.DEBUG:
    urlpatterns  = static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

Base.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>My Blog</title>

    <!-- static CSS & JS -->
    <link rel="stylesheet" href="{% static 'blog/style.css' %}">
    <!-- jquery -->
    <script defer src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" ></script>

    <!-- JS -->
    <script type = "text/javascript" scr="{% static '/blog/js/blog_list.js' %}" ></script>

</head>
<body>
{% block content %}

{% endblock %}
</body>

Archive.html

{% extends 'base.html' %}

{% block content %}
 
<button onclick="myFunction()">Click me!</button>     

{% endblock %}

Blog_list.js (within static/blog/js/)

function myFunction() {
    alert("Hello from a static file!");
  }

CodePudding user response:

In your script tag you misspelled src as scr. change it to src then it may work.

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

Please check your browser console for errors sometimes javascript files are blocked due to some MIME mismatch. if so then remove the type attribute in script tag.

CodePudding user response:

Remove or comment STATIC_ROOT path and add STATICFILES_DIRS and need to correct src argument in img tag

HTML

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

Settings.py

STATIC_URL = '/static/'
# STATIC_ROOT = os.path.join(BASE_DIR,'static/') # active when DEBUG= False

STATICFILES_DIRS = [       # active when DEBUG= True
    os.path.join(BASE_DIR, 'static'),
]

CodePudding user response:

I'm pretty sure granted the CSS is loading it's the leading slash if it's not substituting correctly. Even if it is, you'll want to omit the leading slash for consistency reasons.

As mentioned in another answer, you're also using the wrong attribute for loading the script - it should be src not scr. The mime type is not compulsory, and for standard JS discouraged.

I'd recommend that you only use it when using JS modules or if you need a data block.

Django concatenates the two paths together in the static tag. It's effectively:

STATIC_ROOT [Your template parameter]

So, from this:

<script type = "text/javascript" scr="{% static '/blog/js/blog_list.js' %}" ></script>

To this:

<script src="{% static 'blog/js/blog_list.js' %}"></script>

See the docs here for more info about the static tags (if you haven't already): https://docs.djangoproject.com/en/4.1/ref/templates/builtins/#static

If you want to see how static works under the hood, the source is here: https://github.com/django/django/blob/main/django/templatetags/static.py

Welcome to StackOverflow! I hope you like it here.

  • Related