【问题标题】:Trying to serve django static files on development server - not found尝试在开发服务器上提供 django 静态文件 - 未找到
【发布时间】:2012-08-19 11:08:27
【问题描述】:

我已按照this questionthe documentation 中的说明进行操作,甚至查看了this one,但到目前为止,我无法使用python manage.py runserver 获取我的静态文件。

这些是我的(相关?)设置:

STATIC_ROOT '/home/wayne/programming/somesite/static'
STATICFILES_DIRS ('/home/wayne/programming/somesite/static/styles',
                  '/home/wayne/programming/somesite/static/admin')

在我的 urls.py 中:

from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# The rest of my urls here...
if settings.DEBUG:
    urlpatterns += staticfiles_urlpatterns()

我的 base.html 中有以下代码

    <link rel="stylesheet" type="text/css" href="{% static "styles/main.css" %}">
    {% block styles %}
    {% for sheet in styles %}
    <link rel="stylesheet" type="text/css" href="{% static sheet %}">
    {% endfor %}

我保证我不会产生幻觉:

(.env)wayne:~/programming/somesite/static$ pwd 
/home/wayne/programming/somesite/static 
(.env)wayne:~/programming/somesite/static$ ls 
admin  styles 

但是,当导航到http://localhost:8000/ 时,我的网站缺少样式表,当我转到http://localhost:8000/static/styles/main.css 时,我得到'styles/main.css' could not be found,并尝试导航到localhost:8000/static/localhost:8000/static/styles,它告诉我目录不允许使用索引。

我在这里错过了什么?

【问题讨论】:

  • stackoverflow.com/a/9613606/344286 实际上回答了我的问题 - 但从其他任何问题/文档中都不是很清楚,所以我认为(除非这个问题真的是重复的)它可能对其他人有帮助伙计们。如果没有人提出一个好的答案,我很快就会自己写一个。
  • 您的情况与链接问题中 Mohammed 的情况完全相同,但您提供了更多信息,而且您似乎尝试了更多事情。跨度>

标签: python django


【解决方案1】:

Django 对静态文件的处理仍然有些混乱,尤其是在相关设置的命名方面。

简短的回答是移动您的静态文件;而不是

/home/wayne/programming/somesite/static

把它们放进去

/home/wayne/programming/somesite/yourapp/static

(其中“yourapp”显然是您的主应用程序的名称)。

更长的答案是,我认为您(可以理解)对各种设置感到困惑。 STATIC_ROOT 指的是运行manage.py collectstatic您的静态文件应该结束的位置。在本地开发时,你不需要这个集合(因为你不应该真的需要collectstatic)。无论哪种方式,STATIC_ROOT 都应该始终引用一个空目录。

你的STATICFILES_DIRS 设置几乎可以工作,只是你告诉 Django 有两条路径可以找到静态文件

/home/wayne/programming/somesite/static/styles
/home/wayne/programming/somesite/static/admin

所以当您执行{% static "styles/main.css" %} 时,它会寻找

/home/wayne/programming/somesite/static/styles/styles/main.css
/home/wayne/programming/somesite/static/admin/styles/main.css

显然不会找到它们。 可能起作用的是

STATICFILES_DIRS = ('/home/wayne/programming/somesite/static',)

但没有必要这样做,因为您可以依赖 django.contrib.staticfiles.finders.AppDirectoriesFinder(在 the default STATICFILES_FINDERS 中)并将静态文件移动到应用目录。

希望这能把事情弄清楚一点。

【讨论】:

  • STATICFILES_DIRS = ('/home/wayne/programming/somesite/static',) 确实工作,只要您有不同的STATIC_ROOT。就我个人而言,我更喜欢这种方法来移动静态文件。
猜你喜欢
  • 1970-01-01
  • 2012-03-01
  • 2017-11-15
  • 2011-10-10
  • 1970-01-01
  • 2014-03-13
  • 2013-10-06
  • 1970-01-01
  • 2011-12-04
相关资源
最近更新 更多