我正在尝试提供驻留在STATIC_ROOT文件夹中的文件的缩略图。如果它在MEDIA_URL /缓存中结束并不重要,但是sorl-thumbnail不会从静态文件夹加载图像。
当前代码:
{% thumbnail "images/store/no_image.png" "125x125" as thumb %}
hack有效
{% thumbnail "http://localhost/my_project/static/images/store/no_image.png" "125x125" as thumb %}
我不喜欢黑客,因为 A)它不干(我的项目实际上是从/的子目录提供的) B)它使用http来获取一个只有3个目录的文件,看起来毫无意义效率
答案 0 :(得分:3)
模板过滤器有效。但我不确定,是否每次都从存储中读取。如果是这样,那是不合理的......
from django.template import Library
from django.core.files.images import ImageFile
from django.core.files.storage import get_storage_class
register = Library()
@register.filter
def static_image(path):
"""
{% thumbnail "/img/default_avatar.png"|static_image "50x50" as img %}
<img src="{{ MEDIA_URL }}{{img}}"/>
{% endthumbnail %}
"""
storage_class = get_storage_class(settings.STATICFILES_STORAGE)
storage = storage_class()
image = ImageFile(storage.open(path))
image.storage = storage
return image
答案 1 :(得分:2)
假设您使用的是Django 1.3,您应该查看有关Managing static files的文档
如果您正确设置了所有内容,则可以包含以下图片:
<img src="{{ STATIC_URL }}images/store/no_image.png" />
答案 2 :(得分:2)
我通过将文件从我的视图传递到模板上下文来解决这个问题。
这是我从我的观点调用的示例util函数:
def get_placeholder_image():
from django.core.files.images import ImageFile
from django.core.files.storage import get_storage_class
storage_class = get_storage_class(settings.STATICFILES_STORAGE)
storage = storage_class()
placeholder = storage.open(settings.PLACEHOLDER_IMAGE_PATH)
image = ImageFile(placeholder)
image.storage = storage
return image
您可能会执行与自定义模板标记类似的操作。
答案 3 :(得分:0)
我最终劫持了这样一个事实:它可以从一个URL获取,并编写了我自己的标记,它覆盖了ThumbnailNode上的_render方法:
from django.template import Library
from django.contrib.sites.models import Site
from django.contrib.sites.models import get_current_site
from sorl.thumbnail.templatetags.thumbnail import ThumbnailNode as SorlNode
from sorl.thumbnail.conf import settings
from sorl.thumbnail.images import DummyImageFile
from sorl.thumbnail import default
register = Library()
class ThumbnailNode(SorlNode):
"""allows to add site url prefix"""
def _render(self, context):
file_ = self.file_.resolve(context)
if isinstance(file_, basestring):
site = get_current_site(context['request'])
file_ = "http://" + site.domain + file_
geometry = self.geometry.resolve(context)
options = {}
for key, expr in self.options:
noresolve = {u'True': True, u'False': False, u'None': None}
value = noresolve.get(unicode(expr), expr.resolve(context))
if key == 'options':
options.update(value)
else:
options[key] = value
if settings.THUMBNAIL_DUMMY:
thumbnail = DummyImageFile(geometry)
elif file_:
thumbnail = default.backend.get_thumbnail(
file_, geometry, **options
)
else:
return self.nodelist_empty.render(context)
context.push()
context[self.as_var] = thumbnail
output = self.nodelist_file.render(context)
context.pop()
return output
@register.tag
def thumbnail(parser, token):
return ThumbnailNode(parser, token)
然后从模板:
{% with path=STATIC_URL|add:"/path/to/static/image.png" %}
{% thumbnail path "50x50" as thumb %}
<img src="{{ thumb.url }}" />
...
不是最好的解决方案......: - /
答案 4 :(得分:0)
设置sorl THUMBNAIL_STORAGE的默认值是相同的设置.DEFAULT_FILE_STORAGE。
您必须创建使用STATIC_ROOT的存储,例如,您可以使用'django.core.files.storage.FileSystemStorage'并使用 location = settings.STATIC_ROOT 进行实例化,的 BASE_URL = settings.STATIC_URL 强>
仅在'MyCustomFileStorage'的设置中设置的THUMBNAIL_STORAGE不起作用。所以我必须对DEFAULT_FILE_STORAGE做一些工作。
在settings.py中定义:
DEFAULT_FILE_STORAGE ='utils.storage.StaticFilesStorage'
utils的/ storage.py:
import os
from datetime import datetime
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.core.exceptions import ImproperlyConfigured
def check_settings():
"""
Checks if the MEDIA_(ROOT|URL) and STATIC_(ROOT|URL)
settings have the same value.
"""
if settings.MEDIA_URL == settings.STATIC_URL:
raise ImproperlyConfigured("The MEDIA_URL and STATIC_URL "
"settings must have different values")
if (settings.MEDIA_ROOT == settings.STATIC_ROOT):
raise ImproperlyConfigured("The MEDIA_ROOT and STATIC_ROOT "
"settings must have different values")
class TimeAwareFileSystemStorage(FileSystemStorage):
def accessed_time(self, name):
return datetime.fromtimestamp(os.path.getatime(self.path(name)))
def created_time(self, name):
return datetime.fromtimestamp(os.path.getctime(self.path(name)))
def modified_time(self, name):
return datetime.fromtimestamp(os.path.getmtime(self.path(name)))
class StaticFilesStorage(TimeAwareFileSystemStorage):
"""
Standard file system storage for static files.
The defaults for ``location`` and ``base_url`` are
``STATIC_ROOT`` and ``STATIC_URL``.
"""
def __init__(self, location=None, base_url=None, *args, **kwargs):
if location is None:
location = settings.STATIC_ROOT
if base_url is None:
base_url = settings.STATIC_URL
if not location:
raise ImproperlyConfigured("You're using the staticfiles app "
"without having set the STATIC_ROOT setting. Set it to "
"the absolute path of the directory that holds static files.")
# check for None since we might use a root URL (``/``)
if base_url is None:
raise ImproperlyConfigured("You're using the staticfiles app "
"without having set the STATIC_URL setting. Set it to "
"URL that handles the files served from STATIC_ROOT.")
if settings.DEBUG:
check_settings()
super(StaticFilesStorage, self).__init__(location, base_url, *args, **kwargs)
参考:
https://github.com/mneuhaus/heinzel/blob/master/staticfiles/storage.py
https://docs.djangoproject.com/en/dev/ref/settings/#default-file-storage