How to setup static folder files in Django 1.3 for development server


We can create centralized static folder in PROJECT path and accessed it as “/static/” using development server. To achieve this, you should create “static” folder inside PROJECT folder (not APP folder). Eg :

1
2
3
4
5
PROJECT
  |____APP
  |___ settings.py
  |___ static
  |___ templates

Now, we should configure static in “settings.py” :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# CUSTOMIZATION HERE
import os
# This dynamically discovers the path to the project
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))

# Absolute path to the directory static files should be collected to.
# Don’t put anything in this directory yourself; store your static files
# in apps’ "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
#STATIC_ROOT = os.path.join(PROJECT_PATH, ‘static’)
STATIC_ROOT = ‘/static/’

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = "/static/"

# URL prefix for admin static files — CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = ‘/static/admin/’

# Additional locations of static files
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(PROJECT_PATH, ‘static’),
)

We want this STATIC url path active when in development mode (DEBUG=True). So on “urls.py” :

1
2
3
4
5
6
from django.conf import settings

if settings.DEBUG:
    urlpatterns += patterns(‘django.contrib.staticfiles.views’,
        url(r’^static/(?P<path>.*)$’, ‘serve’),
    )

Now you can freely accessed “/static/” using “{{ STATIC_URL }}” when running development server.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.