2011-09-20 55 views
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个目录的文件,似乎毫无意义地效率低下

+0

米科HELLSING(SORL-缩略图开发商)说我需要instatiate SORL-缩略图,同时BASE_URL,但我一直没能找到有关如何做到这一点的任何文件。 – DarwinSurvivor

回答

2

假设您使用的是Djang Ø1.3你应该看看该文档约Managing static files

如果您设置一切正常,你可以包括你的图片是这样的:

<img src="{{ STATIC_URL }}images/store/no_image.png" /> 
+4

这就是我通常使用的,但我需要重新调整它的大小(因此使用sorl-thumbnail)。如果事实证明无法使用sorl-thumbnail作为静态内容,我可能会被迫创建文件的多个分辨率。 – DarwinSurvivor

+2

@ DarwinSurvivor-你找到了这个问题的答案吗?我也试图创建静态文件的缩略图,但无法弄清楚。 – Clayton

+0

至少与easy_thumbnails这应该不是一个问题:http://packages.python.org/easy-thumbnails/usage.html#non-django-file-objects – arie

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

模板过滤器的作品。但我不确定是否每次都从存储中读取数据。如果是这样,这是不合理的......

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 
0

我结束了劫持的事实,它可以从一个URL获得,并写了我自己的标签,它覆盖_render方法上ThumbnailNode:

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 }}" /> 
... 

不是最巧妙的解决方案...: -/

0

默认值O f设置sorl THUMBNAIL_STORAGE是相同的settings.DEFAULT_FILE_STORAGE。

您必须创建一个使用STATIC_ROOT存储,例如,你可以使用'django.core.files.storage.FileSystemStorage'位置= settings.STATIC_ROOTBASE_URL = settings.STATIC_URL

实例

仅在'MyCustomFileStorage'的设置中设置的THUMBNAIL_STORAGE不起作用。所以我必须做到DEFAULT_FILE_STORAGE,它的工作。

定义在settings.py:

DEFAULT_FILE_STORAGE = 'utils.storage.StaticFilesStorage'

utils的/存储。潘岳:

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