Django static files won't load


i'm a Django newbie working on my first project and having a problem with static files.

I have created a simple auth system using django.contrib.auth consisting of two templates: mysite/templates/index.html and mysite/templates/registration/login.html. I have global static content in mysite/static which I want to be able to access on all templates rendered by all apps.

mysite/templates/index.html contains <img src="{{ STATIC_URL }}pics03.jpg"/> which renders as "static/pics03.jpg" and loads fine when I visit the url localhost:8000/

mysite/templates/registration/login.html contains <img src="{{ STATIC_URL }}pics03.jpg"/> which also renders as "static/pics03.jpg" and does not load when I visit the url "localhost:8000/accounts/login/"

In my I have:

urlpatterns = patterns('',
   url(r'^$', 'mysite.views.home'), # plays index.html template
   url(r'^accounts/login/$', 'django.contrib.auth.views.login'),

In my I have:

PROJECT_DIR = os.path.dirname(__file__)

    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.


STATIC_URL = '/static/'


I was under the impression that Django should be looking for global static content in STATICFILES_DIRS, but it doesn't find the static content for login.html even if I change the url in there to an absolute path to the static folder. Can anyone shed any light on this?

4/18/2012 7:45:39 PM

Accepted Answer

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

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, 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

    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.

4/20/2012 9:32:50 AM

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:

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 collectstatic command to move the static files from throughout your project into that folder. Then you can serve them from there.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow