【问题标题】:Make Django compress with {% static %}使用 {% static %} 使 Django 压缩
【发布时间】:2013-11-13 21:49:46
【问题描述】:

我正在尝试使 django compress 工作,但我相信它不起作用,因为我使用了 {% static %}

我的模板是(我用的是pyjade但没关系):

- load staticfiles
- load compress

| {% compress css %}
link(rel="stylesheet", href="{% static 'less/bootstrap.css' %} ")
link(rel="stylesheet", href="{% static 'timepicker/css/bootstrap-timepicker.min.css'%}")
link(rel="stylesheet", href="{% static 'leaflet/addons/locatecontrol/L.Control.Locate.css' %} ")
link(rel="stylesheet", href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css")
link(href='//api.tiles.mapbox.com/mapbox.js/v1.3.1/mapbox.css', rel='stylesheet')
| {% endcompress %}

还有我的部分设置.py:

PROJECT_DIR = os.path.dirname(os.path.realpath(__file__))

STATIC_ROOT = os.path.join(PROJECT_DIR, '../static')
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(PROJECT_DIR, 'media'),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    #'django.contrib.staticfiles.finders.DefaultStorageFinder',
    'compressor.finders.CompressorFinder',
)

COMPRESS_URL = STATIC_URL
COMPRESS_ROOT = STATIC_ROOT
COMPRESS_STORAGE = "staticfiles.storage.StaticFileStorage"

INSTALLED_APPS = (....,'compressor',....)

即使我$ python manage.py collectstatic 压缩不起作用并吐出原始文件。在docs it says 中,我应该提供我认为我已经给出的绝对路径,不是吗?有人可以帮助进行压缩工作吗?谢谢。 (我对 django 的静态文件不是很熟悉)。


更新

在听了蒂米的评论后,我在设置中启用了COMPRESS_ENABLED = True(和DEBUG=False),它仍然需要找到文件:

UncompressableFileError at /
'less/bootstrap.css ' could not be found in the COMPRESS_ROOT '/Users/diolor/mysite/wsgi/static' or with staticfiles.

请注意静态文件已正确找到并呈现(COMPRESS_ENABLED = False 时)。

我的结构:

mysite/
   wsgi/
      myapp/
         settings.py
         manage.py
         media/
            #js & css files
      static/
         [...]

玩了一段时间后,似乎 compress 对 css 和 {% static %} 有问题。

如果你有 link(rel="stylesheet", href="/static/less/bootstrap.css") 它极大地压缩了样式表,在 link(rel="stylesheet", href="{% static 'less/bootstrap.css' %} ") 它会引发错误。

在 js 上,它渲染得很好:script(type="text/javascript", src='{% static "bootstrap/js/bootstrap.min.js" %}')

【问题讨论】:

  • Compressor 仅在 DEBUG=False 或特别是设置 COMPRESS=True 时才能工作。
  • @TimmyO'Mahony 谢谢你,你是对的。你能检查一下更新吗?

标签: django django-staticfiles django-compressor django-static


【解决方案1】:

问题是你的href 末尾有一个空格,在%}" 之间。如果您仔细查看错误消息,您会看到压缩器正在寻找一个末尾有空格的文件。 (在传单样式表上也是如此。)

【讨论】:

  • 你拯救了我的一天,伙计!
猜你喜欢
  • 2011-09-01
  • 2014-10-24
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 2013-10-08
  • 1970-01-01
  • 2016-03-17
  • 2019-08-06
相关资源
最近更新 更多