Django static files won't load

不打扰是莪最后的温柔 提交于 2019-11-28 21:31:04

Your problem is that you arent listening to the URL "/static/" nowhere in your urls.py

If you serve your application via a webserver like apache or nginx then this is normal as the webserver would handle the static files itself.

For development Django comes with a built-in static server

to urls.py, at the very end add

from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()

What this does is to add the /static/ url and let you serve those without a webserver.

This is equivalent to

url(
    regex=r'^static/(?P<path>.*)$', 
    view='django.views.static.serve', 
    kwargs={'document_root': settings.STATIC_ROOT,}
)

some people will tell you that you need to wrap the URL-rules in a "if settings.DEBUG" to use the dev-only rules, but this isnt needed at all and actually i find that to be a bad advice.

Are you having trouble when using the build in runserver or are you serving using Apache or similar? I've struggled with this a bit. The documentation I follow is: https://docs.djangoproject.com/en/dev/howto/static-files/

The second part is key when you are ready to deploy. You need to define a static root (which will be empty to begin with) and run the manage.py collectstatic command to move the static files from throughout your project into that folder. Then you can serve them from there.

Does changing STATIC_ROOT='' to STATIC_ROOT='/' help?

It seems to me the only difference is that static/pics03.jpg (relative path) exists on the home page, but doesn't on the other.

The absolute path /static/pics03.jpg exists in both cases. If changing STATIC_ROOT doesn't help, just add a / to the beginning of the urls.

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