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 %}

私はハックが好きではありません 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

設定 sorl THUMBNAIL_STORAGE のデフォルト値は同じ settings.DEFAULT_FILE_STORAGE です。

STATIC_ROOTを使用するストレージを作成する必要があります

「MyCustomFileStorage」の設定で設定された THUMBNAIL_STORAGE のみが機能しませんでした。そのため、DEFAULT_FILE_STORAGE を実行する必要がありましたが、うまくいきました。

settings.py で次のように定義します。

DEFAULT_FILE_STORAGE = 'utils.storage.StaticFilesStorage'

ユーティリティ/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

于 2013-02-01T17:08:20.680 に答える
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 に答える