5

我正在尝试提供驻留在我的 STATIC_ROOT 文件夹中的文件的缩略图。它是否最终在 MEDIA_URL/cache 中并不重要,但 sorl-thumbnail 不会从静态文件夹加载图像。

当前代码:

{% thumbnail "images/store/no_image.png" "125x125" as thumb %}

有效的黑客

{% thumbnail "http://localhost/my_project/static/images/store/no_image.png" "125x125" as thumb %}

我不喜欢 hack,因为 A)它并不枯燥(我的项目实际上是从 /B 的子目录提供的)它使用 http 来抓取一个只有 3 个目录之外的文件,看起来毫无意义的低效

4

5 回答 5

3

我通过从我的视图将文件传递到模板上下文来解决这个问题。

这是我从视图中调用的示例 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

您可能会做一些类似于自定义模板标签的事情。

于 2012-04-13T03:59:38.373 回答
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
于 2012-06-23T13:27:30.580 回答
2

假设您使用的是 Django 1.3,您应该查看有关管理静态文件的文档

如果您正确设置了所有内容,您可以像这样包含您的图像:

<img src="{{ STATIC_URL }}images/store/no_image.png" />
于 2011-09-20T19:46:05.917 回答
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 }}" />
...

不是最整洁的解决方案... :-/

于 2012-10-17T12:42:15.287 回答
0

设置 sorl THUMBNAIL_STORAGE 的默认值与 settings.DEFAULT_FILE_STORAGE 相同。

您必须创建使用 STATIC_ROOT 的存储,例如您可以使用'django.core.files.storage.FileSystemStorage'并使用location=settings.STATIC_ROOTbase_url=settings.STATIC_URL进行实例化

只有在“MyCustomFileStorage”设置中设置的 THUMBNAIL_STORAGE 不起作用。所以我不得不对 DEFAULT_FILE_STORAGE 做,它起作用了。

在 settings.py 中定义:

DEFAULT_FILE_STORAGE = 'utils.storage.StaticFilesStorage'

实用程序/存储.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

于 2013-02-01T17:08:20.680 回答