Search code examples
djangodjango-urlsdjango-static

How do I serve static files and dynamic files in Django 1.3 development urls?


I'm a little stumped. In development, I'm trying to serve both static AND dynamic files for my app in DJango 1.3. I love the new static features, but I can't seem to get this to work properly.

When I read the docs, it looks like the following should work. It serves dynamic stuff fine, but not static.

urlpatterns += staticfiles_urlpatterns()

if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^media/dynamic/(?P<path>.*)$', 'django.views.static.serve', {
            'document_root': settings.MEDIA_ROOT,
        }),
   )

Solution

  • In django 1.3 static and dynamic content have been separated. to use the new features, set up your project like this:

    project
     |- app1
     |- media       # exists only on server/folder for dynamic content
     |- static-root # exists only on server/folder for static content
     |- static      # folder for site-specific static content
     |- settings.py
     |- manage.py
     `- urls.py
    

    settings.py

    from os import path
    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')
    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/"
    ADMIN_MEDIA_URL = STATIC_URL + 'admin/' #admin is now served by staticfiles
    STATICFILES_DIRS = (
        ('site', path.join(PROJECT_ROOT,'static')), #store site-specific media here.
    )
    
    #-- other settings --
    INSTALLED_APPS = (
        ...
        'django.contrib.staticfiles',
        ...
    )
    

    urls.py

    from django.conf import settings
    
    #your URL patterns
    
    if settings.DEBUG:
        urlpatterns += staticfiles_urlpatterns() #this servers 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,
            }),
        )