Serving static files for development mode in Django

自古美人都是妖i 提交于 2019-12-06 08:31:47

问题


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.



来源:https://stackoverflow.com/questions/5602263/serving-static-files-for-development-mode-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!