【问题标题】:Django not serving some static filesDjango不提供一些静态文件
【发布时间】:2012-08-11 14:07:43
【问题描述】:

我在使用 Django 时遇到了一个非常奇怪的问题,我的 STATIC_URL/static/,我安装了一个应用程序,使用 pip 作为 -e git+git://github.com/foo/bar.git#egg=bar 将其加载到 virtualenv src 文件夹中。

现在,我正在尝试获取与此应用程序相关的静态文件为 /static/bar/js/something.js,并且 src 文件夹确实有一个 bar/bar/static/bar/js/something.js 文件。即使我 findstatic bar/js/something.js 它给了我一个有效的文件路径。但是,当我使用浏览器访问它时,我是 301 到 /static/bar/js/something.js/ 哪个 404s。

为什么会发生这种情况?

即使使用staticfiles 应用程序,我也能够看到它识别出我的应用程序已安装并且它的static 文件夹存在。但是不知何故,静态文件没有被提供。

【问题讨论】:

  • 你在开发吗?您是否设置了 URL,以便测试服务器为您提供文件? docs.djangoproject.com/en/dev/howto/static-files/…
  • settings.py 中的 STATICFILES_DIRS 中有什么?
  • @TimmyO'Mahony 您能否将其发布为答案,以便我将其标记为正确? :)

标签: django django-staticfiles


【解决方案1】:

确保您拥有set up the django development server to actually server the static files for you

urls.py

from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf goes here ...
urlpatterns += staticfiles_urlpatterns()

【讨论】:

    【解决方案2】:

    尝试使用这个 urlpattern:

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

    【讨论】:

    • 我知道我可以做到,但考虑到virtualenv /path/to/file/ 会在不同的机器/环境上发生变化。
    • 我为这个问题使用了一个配置:settings['INSTALL_ROOT']