2011-09-20 54 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