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
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
- [Django]-How to skip a scenario in Lettuce?
- [Django]-What are these warning for cross-site cookie in my console?
- [Django]-Django β timestamp fields in model
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
]
- [Django]-IPhone POSTing to Django and gets CSRF verification failed
- [Django]-Writing Django Unit Tests for Views
- [Django]-What are the API endpoints ModelViewSet
- [Django]-MySQL database being hit too many times with django query
- [Django]-Django start new project error