Django isn't serving static files, getting 404 errors


Question

I can't seem to get my static files to load from my templates. I've followed the official documentation but I must be missing something.

My directory layout (generated by Django, most files omitted):

myproject
  myproject
    settings.py
    urls.py
  static
    css
      bootstrap.css
      main.css
  templates
    base.html
  myapp1
  myapp2
  ...
  manage.py

My settings.py:

STATIC_URL = 'static/'

I'm referencing my stylesheets like so (from my templates):

{% load staticfiles %}
<link rel="stylesheet" href="{% static "css/bootstrap.css" %}" type="text/css">
<link rel="stylesheet" href="{% static "css/style.css" %}" type="text/css"> 

Which gives this once rendered (in HTML):

<link rel="stylesheet" href="static/css/bootstrap.css" type="text/css">
<link rel="stylesheet" href="static/css/style.css" type="text/css"> 

Yet these links don't actually lead anywhere (when I visit them I get 404 error from Django). I feel that I could fix this by adding something in urls.py, but I thought Django did this automatically when you run the server? What am I missing?

1
13
4/15/2012 8:28:10 PM

Accepted Answer

Have you defined your static files directory in settings.py ?

I'm guessing you have 'django.contrib.staticfiles', in your installed apps.

If you haven't defined your static files dir, you could by doing something like this:

import os.path

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'static'),
)
23
4/15/2012 8:31:05 PM

My problem was solved by adding "STATICFILES_DIRS" in settings.py file

STATIC_URL = '/static/'
STATICFILES_DIRS = ( os.path.join('static'), )

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