Local development Django static files coming from library directory rather than my project

391 Views Asked by At

I have a Django (3.1) app that I've set up to serve static files, that is, myapp/settings.py has

DEBUG = True

.
.
.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
    .
    .
    .
]

.
.
.

STATIC_URL = '/static/'

STATIC_ROOT = 'static/'

But instead of serving files from the static directory of myapp, it's serving static files from /Library/Python/3.7/site-packages/django/contrib/admin/static/. I have tested this by adding files to both directories,

~/Projects/myapp/static/file-from-project.js
/Library/Python/3.7/site-packages/django/contrib/admin/static/file-from-library.js

and then

python3 manage.py runserver

with a template including the lines

<script src="{% static 'file-from-project.js' %}"></script>
<script src="{% static 'file-from-library.js' %}"></script>

and file-from-library.js loads fine but I get a 404 for file-from-project.js. What am I doing wrong here?

Directory structure with the referenced files:

myapp
  /myapp
    settings.py
    .
    .
    .
  /static
    file-from-project.js
    .
    .
    .
  /templates
    .
    .
    .
  manage.py
  .
  .
  .
1

There are 1 best solutions below

7
michjnich On

OK, I see the problem I think.

STATIC_ROOT is an absolute path, not a relative one. if you set it to eg. BASE_DIR / "static" you might get what you want.

I usually set BASE_DIR at the top of my settings.py as it gets used for a few things:

BASE_DIR = Path(__file__).resolve(strict=True).parent.parent

The other thing is that you have DEBUG=True which means it's going to be looking at your STATIC_URL under your app dirs. If you move the file to:

~/Projects/myapp/static/app_folder/file-from-project.js

It should work :)

Edit: I noticed myapp is an app, and not the project name, which makes me wonder what the project is called.

Your static files for development for this structure should probably be in:

~/Projects/myapp/static/myapp/<static file>

When you deploy, obviously DEBUG should be False, but here you should run collectstatic in order to gather all the static files in one place for deployment.