django static files usage


django static files usage

Every website needs to serve the extra files such as images, CSS, JavaScript. The name "static" itself indicates that contents of files do not change. So, in django to work with static files we need to make some configurations in setttings.py file. Django provides app "django.contrib.staticfiles" to help us manage it.

Configuring static files in settings.py 

  1. Add "django.contrib.staticfiles" to "INSTALLED_APPS".
    INSTALLED_APPS = [
        # ...
        'django.contrib.staticfiles',
        # ...
    ]
    
  2.  Add "STATIC_URL
    STATIC_URL = '/static/'
  3. Add "STATICFILES_FINDERS"  to make sure template tag "static" can work  in HTML templates.
    # ...
    INSTALLED_APPS = [
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    ]
    # ...
  4. 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"),
    ]
    # ...
  5. 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)
  6. 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 referece for more detail.

Reference: https://docs.djangoproject.com/en/2.2/howto/static-files/#configuring-static-files

Support Me on Patreon
Blog Archive