15

I'm relatively new to Django (1.4) and I'm having a hard time understanding the philosophy behind static, media, and admin files. The structure of the project is different from one tutorial to another, and same thing for Webfaction(where I'll be hosting my application). I would like to know what is the optimal way to organize it and with least pain and editing while deploying it to Webfaction, what is the point of static media, adn admin files? Thank you in advance

animuson
  • 53,861
  • 28
  • 137
  • 147

3 Answers3

15

In essence you want to serve static files by django in development. Once you're ready to go into production you want the server to do this for you (they are build to do it fast :-))

Here's a basic setup, once you login the server you run the collectstatic command to get all the staticfiles in the static-root folder, which your server points to (see the rewrite rules)

./manage.py collectstatic

settings.py

    from os import path
    import socket

    PROJECT_ROOT = path.dirname(path.abspath(__file__)) #gets directory settings is in

    # Dynamic content is saved to here
    MEDIA_ROOT = path.join(PROJECT_ROOT,'media')
    # if ".webfaction.com" in socket.gethostname():
    #    MEDIA_URL = 'http://(dev.)yourdomain.com/media/'
    # else:
        MEDIA_URL = '/media/'

    # Static content is saved to here --
    STATIC_ROOT = path.join(PROJECT_ROOT,'static-root') # this folder is used to collect static files in production. not used in development
    STATIC_URL =  "/static/"
    STATICFILES_DIRS = (
        ('', path.join(PROJECT_ROOT,'static')), #store site-specific media here.
    )

    # List of finder classes that know how to find static files in
    # various locations.
    STATICFILES_FINDERS = (
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    #    'django.contrib.staticfiles.finders.DefaultStorageFinder',
    )

settings_deployment.py

from settings import *

DEBUG = False
TEMPLATE_DEBUG = DEBUG
MEDIA_URL = "http://yourdomain.com/media/"

urls.py

...other url patterns...

if settings.DEBUG:
    urlpatterns += staticfiles_urlpatterns() #this serves static files and media files.
    #in case media is not served correctly
    urlpatterns += patterns('',
        url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
            'document_root': settings.MEDIA_ROOT,
            }),
    )

django.conf (lighttpd, this could be apache or nginx) but I believe webfaction has an app service to set this up easily

$HTTP["host"] =~ "(^|\.)yourdomain\.com$" {
    fastcgi.server = (
        "/django.fcgi" => (
            "main" => (
                "socket" => env.HOME + "/project/project.sock",
                "check-local" => "disable",
            )
        ),
    )
    alias.url = (
        "/media" => env.HOME + "/project/media",
        "/static" => env.HOME + "/project/static-root",
    )

    url.rewrite-once = (
        "^(/media.*)$" => "$1",
        "^(/static.*)$" => "$1",
        "^/favicon\.ico$" => "/static/img/favicon.png",
        "^(/.*)$" => "/django.fcgi$1",
    )
}
Hedde van der Heide
  • 21,841
  • 13
  • 71
  • 100
  • 2
    Something worth noting is that if you accidentally forget the trailing comma on the STATICFILES_DIRS item, collectstatic will start copying everything instead of just what's in the static folders. It took me a while to notice so I thought I'd mention it. – Soviut Feb 28 '13 at 00:11
4

Static files are files needed by your applications that server can serve without modifications, like custom JS scripts, icons, applets, etc. The best way to use it is to place static files in a "static" folder in each of your app's folder. Like this, the test server will find them there, and if you deploy on a production server, you'll just have to run python manage.py collectstatic to copy them all in the root static folder defined in you settings.py

Media files are those uploaded by the users of your applications, like avatar's pics, etc.

Admin files are static files used by Django admin, django test server will just find them, but on production, you'll have to copy or link to this folder for the admin to actually work.

Hope it helps you see things better...

Lapin-Blanc
  • 1,945
  • 1
  • 17
  • 26
  • Can't I just create a single folder where I put all the css and javascript code for my web pages instead of seperating them in folders? I mean, i have the site layout ready but i just need to make it work with Django. Should I separate the files? –  May 05 '12 at 09:58
  • You must put the static files in a separate directory than the python code or the templates because you don't want to expose your code but other than that you can lay them out the way you want. You should read that: https://docs.djangoproject.com/en/1.4/howto/static-files/ – Claude Vedovini May 05 '12 at 11:46
  • read how filefinders work in the django docs, it's all well explained there, with the example I posted below it should make sense, django will follow the hierarchy you use in the filefinder tuple and collect ALL these files to the static-root folder, but in a dev project it makes perfect sense to keep feels separated to where they belong.. – Hedde van der Heide May 05 '12 at 14:48
1

My config is:

1.settings.py

    # Absolute filesystem path to the directory that will hold user-uploaded files.
    # Example: "/var/www/example.com/media/"
    MEDIA_ROOT='/media/'

    # URL that handles the media served from MEDIA_ROOT. Make sure to use a
    # trailing slash.
    # Examples: "http://example.com/media/", "http://media.example.com/"
    MEDIA_URL = '/media/'

    # 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: "/var/www/example.com/static/"
    STATIC_ROOT = '/static/'

    # URL prefix for static files.
    # Example: "http://example.com/static/", "http://static.example.com/"
    STATIC_URL = '/static/'


    # Additional locations of static files
    STATICFILES_DIRS = (
        '/'.join(__file__.split(os.sep)[0:-2]+['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.
    )

    # List of finder classes that know how to find static files in
    # various locations.
    STATICFILES_FINDERS = (
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    #    'django.contrib.staticfiles.finders.DefaultStorageFinder',
    )

2.urls.py

    from django.conf import settings
    if settings.DEBUG:
       from django.contrib.staticfiles.urls import staticfiles_urlpatterns
       urlpatterns += staticfiles_urlpatterns()

AND my site dir is like this:

    root
    │  manage.py
    │
    ├─media
    ├─my_django_py3
    │    settings.py
    │    urls.py
    │    views.py
    │    wsgi.py
    │    __init__.py
    │
    ├─static
    │      9gq05.jpg
    │      ajax.js
    │      favicon.gif
    │
    ├─templates
    └─utils
zoumi
  • 175
  • 1
  • 8