无法加载静态文件

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也无法加载静态文件

Nextjs:无法从静态文件夹加载图像

Django:无法从 DigitalOcean Droplet 上的模板加载静态文件

无法在弹性豆茎上加载带有瓶子的静态文件

Django设置 DEBUG=False后静态文件无法加载解决

Spring boot 静态资源无法加载