如何在Django 1.3开发网址中提供静态文件和动态文件?

时间:2011-06-22 19:48:38

标签: django django-urls django-static

我有点难过。在开发中,我正在尝试为DJango 1.3中的应用程序提供静态和动态文件。我喜欢新的静态功能,但我似乎无法使其正常工作。

当我阅读文档时,看起来以下内容应该有效。它可以很好地提供动态的东西,但不是静态的。

urlpatterns += staticfiles_urlpatterns()

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

2 个答案:

答案 0 :(得分:7)

在django 1.3中,静态和动态内容已被分开。要使用新功能,请按以下方式设置项目:

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,
        }),
    )

答案 1 :(得分:1)

从settings.py检查STATIC_URL,值是多少?