[Fixed]-Django static files won't load

21👍

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.

👤krs

1👍

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/stable/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.

0👍

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.

Leave a comment