[Django]-Is there a better way to load Django static directories for multiple apps than this? Thank you

1πŸ‘

βœ…

You can add custom static file finder that would sort you out, but generally if you have /static folder inside of the app it should be discovered by

django.contrib.staticfiles.finders.AppDirectoriesFinder

as documented

The default will find files stored in the STATICFILES_DIRS setting
(using django.contrib.staticfiles.finders.FileSystemFinder) and in a
static subdirectory of each app (using
django.contrib.staticfiles.finders.AppDirectoriesFinder). If multiple
files with the same name are present, the first file that is found will be
used

Source

πŸ‘€iklinac

2πŸ‘

A better practice is to put all your static files in the same folder in your root directory instead of each app:

# ...
β”œβ”€β”€ app1
β”œβ”€β”€ app2
β”œβ”€β”€ project
β”œβ”€β”€ manage.py
β”œβ”€β”€ media
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ static
β”‚   β”œβ”€β”€ css
β”‚   β”œβ”€β”€ icons
β”‚   β”œβ”€β”€ img
β”‚   β”œβ”€β”€ js
β”‚   └── vendor

Then in your settings.py assign this variable:

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

staticfiles_dirs sets the directory and tells Django where to look up for your static files, in this example, our folder is named β€˜static’ in our root directory, os.path.join will join the base directory(root) with static.

BTW STATIC_ROOT is usually used in a production environment, when you run β€˜collectstatic` command, all static files including your 3rd party apps will be copied to this β€˜staticfiles’ folder.

Also, you can put templates of each app into the same folder in a similar way:

# root 
└── templates
    β”œβ”€β”€ app1
    β”œβ”€β”€ app2
    β”œβ”€β”€ app3
    β”œβ”€β”€ base.html
    └── index.html

And in your settings.py, add the directory of β€˜templates’ folder.


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': { # ...
            ],
        },
    },
]

Personally, I think this would be much cleaner.

You can reference my project for the file structure:
here

πŸ‘€convers39

0πŸ‘

I recommend to serve static files from Django project root directory as shown below. *My answer explains how to load CSS and JavaScript files in Django in detail:

django-project
 |-core
 |  β””-settings.py
 |-my_app1
 |-my_app2
 |-static # Here
 |  β””-my_app1
 |     |-css
 |     |  β””-hello.css
 |     β””-js
 |        β””-hello.js
 |
 β””-templates
    β””-index.html

Then, set BASE_DIR / 'static/' to STATICFILES_DIRS in settings.py as shown below:

# "settings.py"

STATIC_URL = 'static/'
STATIC_ROOT = 'staticfiles/'
STATICFILES_DIRS = [
    BASE_DIR / 'static/' # Here
]

Leave a comment