./manage.py 测试不提供静态文件?

./manage.py test doesn't serve static files?

我在一个项目中发现了以下代码,删除它会导致测试失败:

if 'test' in sys.argv:
    urlpatterns += patterns('',
                            (r'^static/(?P<path>.*)$', 'django.views.static.serve',
                             {'document_root': os.path.join(settings.BASE_DIR, 'viewer/templates/static')}),
                            )

出于某种原因,即使在 ./manage.py runserver 上工作正常,./manage.py test 也不会在没有此行的情况下提供静态文件。为什么会这样?

您需要为 manage.py test 指定那些行的原因是因为提供静态文件不是默认的 django 行为。

如果您是 运行 服务器 manage.py runserverstatic content is only served if DEBUG=True

提供此功能是为了在开发模式下为用户提供帮助,不建议在生产模式下使用。

来自上面的link:

Serving the files

In addition to these configuration steps, you’ll also need to actually serve the static files.

During development, if you use django.contrib.staticfiles, this will be done automatically by runserver when DEBUG is set to True (see django.contrib.staticfiles.views.serve()).

This method is grossly inefficient and probably insecure, so it is unsuitable for production.

See Deploying static files for proper strategies to serve static files in production environments.