Serving static files for development mode in Djang

2020-07-18 05:35发布

问题:

I'm having trouble serving static files in development mode in Django. I do know that this is not a setting that should be used in a production server, so don't worry. For now however I'd like to stick to it.

The relevant parts of settings.py are:

MEDIA_URL = '/media/'
STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__) + '/..'), 'media')
STATIC_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__) + '/..'), 'static')

And of urls.py:

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

So the static files are located for now in the directory named static right outside the project folder. I verified that STATIC_ROOT is evaluated to an appropriate value. I've double checked that the folder exists.

However when pointing my browser to the address localhost:8000/static/js/somefile.js, I get the dreaded 404 Page Not Found with the message 'js/somefile.js' could not be found.. Could you please suggest some reasons to this behaviour?

Thanks in advance.

EDIT:

I think I know where the problem may be: The thing is that in development mode Django attempts to look for the files from the STATIC_URL in the static/ subdirectories of all the installed apps. However I've added some additional files to my STATIC_ROOT and these are not served at all. Maybe there is some clash.

EDIT (2):

This must be it. When I run the server with ./manage.py runserver --nostatic it works, that is it actually serves the files from the STATIC_ROOT directory. What can I do about it? The problem is that just as I try to keep all my template files separate from the project itself I try to do the same with certain css and js files...

回答1:

It doesn't work, because what I was trying to do wasn't very wise.

That's how it should be configured. settings.py:

MEDIA_URL = '/media/'
STATIC_URL = '/static/'

MEDIA_ROOT = 'media.mydomain.com'
STATIC_ROOT = 'static.mydomain.com'

STATIC_DIRS = (
    os.path.join(os.path.abspath(os.path.dirname(__file__) + '/..'), 'static'),
)

All the files remain in place, exactly where they were.



回答2:

I had a similar problem, adding an explicit reference to the media location in my urlconf as per this fixed the problem for me.