Adding CSS templates to Django – A Tutorial for Dummies

I have seen a lot of pages and stackoverflow questions that just want to know… how in hell do I get a CSS template to work with Django, even on a basic level? I found the official documentation for Django static files a bit confusing. So I’ve laid out the steps here, along with some basic tips. This will work for offline development scenarios – I haven’t deployed my project on a *real* server yet. 😉

Without further ado, here we go:

  1. The default location for your static files (CSS style sheets, images) is per app: for each app, create a static subdirectory, and put all your static files there. These apps need to be listed in your INSTALLED APPS setting.
  2. Place your statics files in the appropriate directory. Here the *.css files for app books are located in the static subdirectory, and the images are located in a dedicated images subdirectory within .
  3. Directory Structure

  4. Add django.contrib.staticfiles to your INSTALLED_APPS, in your settings.py file (if it isn’t there already).
  5. INSTALLED_APPS = (
        ...
        'django.contrib.staticfiles',
        'MyWebsite.books'
    )
    
  6. If necessary, add explicit local paths to STATICFILES_DIRS in settings.py
  7. # URL prefix for static files.
    # Example: "http://example.com/static/", "http://static.example.com/"
    STATIC_URL = '/static/'
    
    # Additional locations of static files
    STATICFILES_DIRS = (
        'C:/workspace/MyWebsite/src/MyWebsite/static',
        # 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.
        )
    
  8. When you refer to the files in your templates, you will use the tag {{ STATIC_URL }}. Examples for a CSS stylesheet and an image:
  9. 
    Display Authors
        	<link href="{{ STATIC_URL }}style1.css" rel="stylesheet" type="text/css" />
    <img alt="" src="{{ STATIC_URL }}images/photo.jpg" />
    
    
  10. As shown above, CSS tags are placed below the title tag.
  11. This should work now. Good luck!
Advertisements

2 Responses

  1. […] Read More: Adding CSS templates to Django – A Tutorial for Dummies « Code … […]

  2. Hi, thanks for your tutorial. Most of the places I am seeing are giving a similar solution to this, but I still can’t get it working. Its acting as though STATIC_URL is being replaced with nothing! Please help.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: