Liondancer
Liondancer

Reputation: 16469

dealing with static files in Django

Currently I have my settings.py regarding static files set up like so

STATIC_ROOT = ''

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

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

STATIC_URL = '/static/'

From reading the documentation and various blogs my understanding is that STATIC_ROOT is where the static files go. It is the absolute path to the directory where collectstatic will collect static files for deployment (OUTPUT). I am not sure what to put this value as

For STATICFILES_DIR This setting defines the additional locations the static files app will traverse if the FileSystemFinder finder is enabled. So I would NEED a STATICFILES_FINDER field in my settings.py and in that field would be

('django.contrib.staticfiles.finders.FileSystemFinder',
 'django.contrib.staticfiles.finders.AppDirectoriesFinder')

However, by default STATICFILES_DIR is not included in my settings.py so I added it in.

For STATIC_URL is the URL to use when referring to static files located in STATIC_ROOT. I simply left it as the default setting because I am not sure how edit this.

I am not sure how to edit my settings.py regarding static files in order to display them onto a webpage. What is a "Best Practices" way to include static files onto a webpage?

ex: {% static "static/css/default.css" %}

I read a bit about namespacing as well but I am confused about this too

ex:

STATICFILES_DIR = (
    ("asserts",  os.path.join(BASE_DIR, 'static')),
    )

Upvotes: 2

Views: 374

Answers (1)

Arseniy
Arseniy

Reputation: 1778

Best practice would be keeping each app's static files in it's own 'static' dir and running manage.py collect_static each time some static file changes.

Then, if you use default storage your files would be copied into STATIC_ROOT directory. (But you might use custom storage, for ex for storing static files on Amazon S3 cloud)

And finally, STATIC_URL defines how your static files would be accessible from outside. In case of django dev server- it has static files app, that serves them under STATIC_URL location. In case of production server you definitely want to serve static files with either nginx/apache or with amazon S3/cloudfront (or other cloud services). In case ouf serving with nginx/apache, you must set STATIC_URL so {% static "static/css/default.css" %} will be replaced with the url relative to STATIC_ROOT, at the same time you should have this STATIC_URL location overriden in nginx/apache settings, so when final user tries to access it, it gets static file served w/o even touching django. In case of custom storage- this storage might provide it's own url (to S3 cloud for ex).

Upvotes: 1

Related Questions