Joseph Adam
Joseph Adam

Reputation: 1652

Static css and js loads when using STATICFILES_DIRS not STATIC_URL

My settings.py is

STATIC_URL = '/some_location/static/'

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

My urls.py

urlpatterns = [ multiple path ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

My base .html with the directory structure is,

enter image description here

My directory root from image above

-project directory
-->appname
-->static
---->css
------>master.css
---->js
----->master.js

I use pycharm IDE.

The error message I get is 

"GET /some_location/static/js/master.js HTTP/1.1" 404 1736
"GET /some_location/static/css/master.css HTTP/1.1" 404 1742

When I use the above location /some_location/static/js/master.js in the browser I get to see the file content.

What I do to correctly load the .css and .js on the development server in Pycharm?

Update 1:

This seems to have worked, but not sure why. Can someone clarify why one works but not the other

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

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

Upvotes: 1

Views: 168

Answers (1)

dirkgroten
dirkgroten

Reputation: 20692

Here's hopefully some clarification:

  • STATIC_URL tells Django which url it should prepend for all links to static files when rendering {% static %} links. For development, it's easiest to set it to /static/. On your production settings, it would probably point to a cloud provider url behind a CDN (e.g https://my-cdn.cloudflare.net/static/).
  • STATIC_ROOT tells the collectstatic management command where to copy all the static files of your project. This is usually not relevant on your development machine (you serve the static files directly from your project) but is relevant for deploying in production: you'll want to copy all your static files to a location outside of your project directory (e.g. a cloud storage bucket like S3 of Amazon).
  • Your static files should be located inside a static directory inside each of your apps (ie. in your case the appname/static directory). If you also have a separate directory, like static directly in your project BASE_DIR, then you tell Django that using STATICFILES_DIRS. This tells runserver to also look there. On production, it tells collectstatic where to gather all static files from.

So to summarise: STATIC_URL/path_to/my_file is the URL a user sees in the browser, when using the built-in Django runserver, STATIC_URL is stripped and path_to/my_file is searched in all the app static directories and directory listed in STATICFILES_DIRS.

I've also written a blog post about this.

Upvotes: 1

Related Questions