Django Static Files Usage¶
setttings.py file. Django provides app "
django.contrib.staticfiles" to help us manage it.
Configuring static files in settings.py¶
- Add "django.contrib.staticfiles" to "INSTALLED_APPS".
INSTALLED_APPS = [ # ... 'django.contrib.staticfiles', # ... ]
- Add "STATIC_URL"
STATIC_URL = '/static/'
- Add "STATICFILES_FINDERS" to make sure template tag "static" can work in HTML templates.
# ... STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] # ...
- Add extra static directories using "STATICFILES_DIRS". In below example we added a directory "static" to static files finder which is located at the root level of our project.
# ... STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] # ...
- Add static root to root project urls.py to make available static files during development like below
from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
- Serving files uploaded by a user during development
from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
That's it folks, let's meet in the next article. Check the below reference for more detail.