无法加载静态文件
Posted
技术标签:
【中文标题】无法加载静态文件【英文标题】:Unable to load static files 【发布时间】:2015-03-10 17:52:17 【问题描述】:我在settings.py
添加了以下内容:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')
在urls.py
:
urlpatterns = patterns('^/static/$',
# ... the rest of your URLconf goes here ...
url(r'^$', home, name='home'),
url(r'^admin/', include(admin.site.urls))
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
在models.py
:
class Search(models.Model):
question = models.URLField()
query = models.CharField(max_length=255)
在views.py
:
def home(request):
print ' base dir %s' % BASE_DIR
print ' static dir %s' % STATIC_URL
form = SearchForm()
return render_to_response('base.html', 'form': form,
context_instance=RequestContext(request))
和templates/base.html
:
% load staticfiles %
<head>
<link href=" STATIC_URL bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<script src=" STATIC_URL bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<title>Walker</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="form-group">
<form name="query">
form.as_p
</form>
</div>
</div>
</div>
</div>
</body>
我运行./manage.py collectstatic
没有问题,正在创建文件夹static
。
当我执行./manage.py runserver
时,我可以在终端中看到这个错误:
基本目录 home/my/code/walker
静态目录 /static/
"GET /static/bootstrap/js/bootstrap.min.js HTTP/1.1" 404 1691
模板加载正确。但是引导程序没有
几个小时都想不通我需要做什么
【问题讨论】:
DEBUG 设置为 True 吗? @cziemba 是的,编辑问题 @micgeronimo 您生成/收集的静态文件夹的布局是什么?匹配STATIC_ROOT/bootstrap....
吗?
@Yuji'Tomita'Tomita,是的
【参考方案1】:
如果您将静态文件存储在app/static
以外的位置,我认为您需要在您的settings.py
中指定STATICFILES_DIRS
,否则它们将不会被收集:
STATICFILES_DIRS = (
"/path/to/static", #collectstatic will find any app/static directories so do not add those here
)
default 为空。
另外,使用href="% static 'my-static.css' %"
而不是 STATIC_URL
指定静态文件
您也可以使用findstatic 来检查您的静态文件是否能够被服务器定位。
【讨论】:
以上是关于无法加载静态文件的主要内容,如果未能解决你的问题,请参考以下文章
Django:无法从 DigitalOcean Droplet 上的模板加载静态文件