static files not found error in django

Question:

I know that this problem has already been asked several times here. I have searched and read a number of answers but no help. I guess, I am missing something very basic.

In my settings.py, I have:

STATIC_URL = '/static/'
STATIC_ROOT = join(APPS_DIR, "static/")
# STATICFILES_DIRS = [join(APPS_DIR, 'static')]

MEDIA_ROOT = join(APPS_DIR, 'media')
MEDIA_URL = "/media/"

In my config/urls.py, I have:

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

I have a file located at /static/core/js/jquery_countdown/jquery.countdown.min.js which I am trying to load in template as below:

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<script type="text/javascript" src="{% static 'core/js/jquery_countdown/jquery.countdown.min.js' %}"> </script>

The top of the same template looks like

{% extends "contest/base.html" %}
{% load static %}

This results in following server error:

[23/Mar/2018 10:12:08] "GET /static/core/js/jquery_countdown/jquery.countdown.min.js HTTP/1.1" 404 1858

What am I missing?

Asked By: inquilabee

||

Answers:

You are searching for static files in app directories only but have your file in global static files. You should use the commented STATICFILES_DIRS setting to specify all places to search for static files.

Answered By: polarise

Create folder static_files in your app directory. And place all your static files inside it. Then use the following settings

STATIC_URL = '/static/'
STATIC_ROOT = join(APPS_DIR, "static/")
STATICFILES_DIRS = [join(APPS_DIR, 'static_files')]

If it does not solve your issue, then run the command python manage.py collectstatic. It will copy all the static files (Not only from your app but also from django admin, third party apps etc) to the STATIC_ROOT folder.

Details

For local serving, django server will look in to the STATICFILES_DIRS. So you dont need to run the python manage.py collectstatic command. All the external apps may have STATICFILES_DIRS where they place their static files. For production server you need to collect all these static files scattered around all your apps in to a single place. Thats what python manage.py collectstatic command will do. It will copy all the static files in to STATIC_ROOT directory

Answered By: Aneesh R S

I found that this worked for me. (Development)
(I chose to name it "zStatic" to keep it at the bottom of the root (project folder), so that it isnt amidst all my apps. Easier to locate.)

Settings.py

STATIC_URL = 'zStatic/'  
STATICFILES_DIRS = (  
BASE_DIR/'zStatic',  
)

INSTALLED_APPS = 
[
...
'django.contrib.staticfiles',
...
]

base.html (base template)

<head>  
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'css/mycss.css' %}"> 
</head>
Answered By: Mike U-man