How do I use CSS in Django?

How do I use CSS in Django?

I am creating my application using Django, and am wondering how I can make Django use my CSS file? What settings do I need to do to make Django see the css file?
NB: On a local machine

Solutions/Answers:

Answer 1:

If you’re using the development server follow the django project’s how-to guide for managing static files to setup your URL’s, then reference you media files in the template — say, an image inside an image folder from /site_media/images/foo.gif.

Answer 2:

More generally stated, you’re asking how to serve a static file from Django. If you are running under Apache, you should read http://docs.djangoproject.com/en/dev/howto/deployment/modpython/

If you are running the development server (say, on your laptop), read http://docs.djangoproject.com/en/dev/howto/static-files/

Do note the big, fat disclaimer regarding the Django development server:

  • Using this server is inefficient and insecure.
  • Do not use this in a production setting.
  • Use this only for development.

Answer 3:

This caused me problems too for a while (404 not found errors). The missing bit for me was to edit the STATICFILES_DIRS tuple in settings.py to give me this:

STATICFILES_DIRS = (
    # 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.
    os.path.join(os.path.dirname(__file__),'media').replace('\\','/'),
)

This then picked up my CSS files in a folder called ‘media’ that was at the top level of my django project.

I also had:

MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/media/'

(make sure you have the leading / above in STATIC_URL)

Of course, as said above, you need to have the CSS file properly included from your html files. I had:

<link href="{{ STATIC_URL }}css/ea_base.css" rel="stylesheet" type="text/css" media="screen" />

Answer 4:

What settings do i need to do to make Django see the css file?

None.

Make sure your template includes the CSS file (as standard HTML does) and put the CSS file on the media server.

To clarify: With Django it is highly recommended that you serve all your media (everything that isn’t dynamic html) from a different server instance. How you implement that is completely up to you but most people create a subdomain.

Answer 5:

The official django docs didn’t help me. Hope the blog post “Django: How to serve static files” helps some of you.

Answer 6:

Well the easiest way to use css with django, is to add it to your templates as static-files.

But it’s a bit like ajax, I didn’t find anything that tells how to include it in a standard way.

There is a css-compressor module for django if you want to optimise its size.

References