为什么我不能让我的静态目录与django 1.3一起使用?

时间:2011-06-15 20:11:43

标签: python django web static url-pattern

这个问题很简单,但我无法弄清楚

添加到我的urlpatterns

url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/user/www/site/static'})

我的main.css是:/home/user/www/site/static/css/main.css

当我访问http://localhost:8000/static/

我得到:404:此处不允许使用目录索引。

当我访问http://localhost:8000/static/css/main.css

我得到:404:找不到'css / main.css'

我做错了什么?

修正了它:

url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT } ),
在settings.py

# 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(CURRENT_PATH, 'static') #=='/home/user/www/site/static'

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

正如你所看到的,我唯一真正改变的是从STATIC_URL ='/ static /'到STATIC_URL ='/ mystatic /'

注意:当我到达http://localhost:8000/mystatic时...我得到与上面相同的错误

我认为STATIC_URL应该是'/ static /',以便您可以在模板中使用{{STATIC_URL}} ...我真的不明白为什么这个修复工作有效以及为什么我必须进行更改我做了....

为什么这样做?

3 个答案:

答案 0 :(得分:8)

如果您正在使用内置开发网络服务器(即使用manage.py runserver运行它),Django将在开发过程中处理静态文件。

请注意,STATIC_ROOT是Django收集静态文件的路径,而不是它提供文件的路径。你不应该自己保持STATIC_ROOT!您可以在the Django documentation

中详细了解相关内容

通常,您无需使用内置服务器将django.views.static.serve添加到您的网址。

除了STATIC_ROOT之外,静态文件应该放在其他地方。您可以将它们放在myapp/static路径中(即在单个应用程序静态文件下)。您还可以为整个项目指定静态文件夹(例如/path/to/project/proj_settings),并将STATICFILES_DIRS中的settings.py更新为:

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_DIR, 'proj_static'),
)

然后,您可以将css/main.css文件放入/proj_static/css/main.css。 Django内置的webserver将从那里服务/static/

在制作过程中,您应该通过运行STATIC_ROOT来收集manage.py collectstatic中的所有静态文件。然后,您可以通过您的网络服务器(例如nginx,Apache)直接提供该文件夹,而不是通过Django。

答案 1 :(得分:0)

您应该在settings.py

中设置STATIC_URL

在你的情况下,它必须是

STATIC_URL = '/static/'

答案 2 :(得分:0)

主要有两步:

  1. 检查STATIC_ROOT路径:

    该文件是否存在? /home/user/www/site/static/css/main.css

    如果没有,你应该运行“python manage.py collectstatic”将静态文件复制到STATIC_ROOT路径

    如果“collectstatic”无法将css文件复制到STATIC_ROOT路径,则应在“STATICFILES_DIRS”中检查源css路径

  2. 在开发环境中
  3. ,(使用runserver启动Web服务器),确保:

    a)settings.py:INSTALLED_APPS包括:'django.contrib.staticfiles'

    b)urls.py:urlpatterns + = staticfiles_urlpatterns()

  4. 我猜你没有配置步骤2.b. 你的方法应该没问题,但它是硬编码的,

    url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT } ),
    

    在django的文件中已经提到:

    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    urlpatterns += staticfiles_urlpatterns()