Django 建议我,如果我只使用一台服务器 (Apache) 来提供动态和静态文件,那么 I should serve static files using django.contrib.staticfiles
.
所以在我的 settings.py
中,我已经将 django.contrib.staticfiles
加载到我的 INSTALLED_APPS
和 django.core.context_processors .static
到我的 TEMPLATE_CONTEXT_PROCESSORS
。
我在管理模板中注意到它链接到这样的静态文件(来自 index.html
):
{% load i18n admin_static %}
{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}" />{% endblock %}
但是查看模板标签admin_static
,它只是static
的包装器:
from django.conf import settings
from django.template import Library
register = Library()
if 'django.contrib.staticfiles' in settings.INSTALLED_APPS:
from django.contrib.staticfiles.templatetags.staticfiles import static
else:
from django.templatetags.static import static
static = register.simple_tag(static)
所以我得出结论,因为每个管理静态文件都带有 admin/...
前缀,所以完整路径(对于我的情况)应该是
/usr/lib64/python2.7/site-packages/django/contrib/admin/static
所以我在 settings.py
中将该路径设置为我的 STATICFILES_DIRS
,但 Apache 仍然不会提供任何静态文件(在重新启动服务器之后)。我的逻辑哪里出错了?
最佳答案
感谢 Daniel Roseman 的解释并让我有机会自学(现在我不会忘记!):-)。
起初我真的很困惑,我不知道你必须先收集静态文件,然后告诉 Apache 服务它。我认为只需使用 STATICFILES_DIRS
并将 static
应用程序包含在 settings.py
中就足够了。
这就是我的做法(如果我可以做得更好,请告诉我):
在settings.py
STATIC_ROOT = '/var/www/localhost/htdocs/mysite/static/'
STATIC_URL = '/static/' # default
似乎 Django 已经知道在哪里收集管理文件,你不需要在 STATICFILES_DIRS
中指定任何东西,除非你需要提供你自己的自定义文件(我不需要,因此我以前没有使用 Django 中的静态文件的经验)。
然后在 /var/www/localhost/htdocs/mysite/
键入 python manage.py collectstatic -l
。 -l
表示创建指向所有找到的静态文件的符号链接(symbolic link),而不是将其复制过来(节省一些空间)。
接下来编辑 Apache 配置文件(通常是 httpd.conf
)并添加 STATIC_URL
信息。我的 Django 配置文件如下所示:
Alias /static/ /var/www/localhost/htdocs/mysite/static/
#In the form of...
#Alias STATIC_URL STATIC_ROOT
<Directory /var/www/localhost/htdocs/mysite/static>
Order deny,allow
Allow from all
</Directory>
WSGIScriptAlias / /var/www/localhost/htdocs/mysite/mysite/wsgi.py
WSGIPythonPath /var/www/localhost/htdocs/mysite
<Directory /var/www/localhost/htdocs/mysite/mysite>
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
然后重启Apache,大功告成!
关于python - 如何在 Django 1.4(使用一台 Apache 服务器)中使用 django.contrib.staticfiles 提供管理静态文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9959875/