Django: GET css returns 404?

fildred13 picture fildred13 · Mar 26, 2013 · Viewed 9.3k times · Source

I am developing a Django site and after a series of edits I ran my server again when suddenly - no css! The server still displays the html site, of course, but the css all across the site is throwing a 404 error. My static files information in my settings.py wasn't edited at all:

import os
# hack to accommodate Windows
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8')).replace('\\', '/')

STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    os.path.join(CURRENT_PATH, 'static'),
)

My base template does a simple call for the file based on the static file directory:

<link rel="Stylesheet" type="text/css" href="{{ STATIC_URL }}css.css" />

And lastly, of course, here is a quick breakdown of my pertinent directory structure, since I suspect the error is some kind of directory issue:

-project-
     settings.py
     -static-
         css.css
     -templates-
         base.html
         index.html

I've only provided the location of index.html, but the templates folder of course is filled with directories for various templates/pages.

I'll keep this question updated with information as I troubleshoot/receive answers.

Answer

Matt Seymour picture Matt Seymour · Mar 26, 2013

There are a number of things you need to do in order to get the static urls working on the development platform.

For this i would recommend looking through and reading this link. https://docs.djangoproject.com/en/dev/howto/static-files/

As well as this you also need to return a request context from your view.

Note that within your urls.py file you will also need to add the line.

urlpatterns += staticfiles_urlpatterns()

This line allows the URL's module within a development server to serve static files.

I also notice that you have a variable within your os.path.join code. os.path.join will already be pointing at you development directory if you are using a basic django setup.

You should be able to use:

# Additional locations of static files
STATICFILES_DIRS = (
    os.path.join('static'),
)

Note: Also make sure your views are a returning a request context, as this is required for the STATIC_URL variable to be populated. Likewise, ensure you have all the TEMPLATE_CONTEXT_PROCESSORS added into the settings.py file