2011-09-20 14 views
5

Estoy tratando de mostrar la miniatura de un archivo que reside en mi carpeta STATIC_ROOT. En realidad, no importa si termina en MEDIA_URL/caché, pero sorl-thumbnail no cargará la imagen desde la carpeta estática.Uso de imágenes estáticas con sorl-thumbnail

código actual:

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

truco que funciona

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

no me gusta el truco porque A) No es seco (mi proyecto es en realidad sirve a partir de un subdirectorio de/ B) Está utilizando http para tomar un archivo que está a solo 3 directorios de distancia, parece inútilmente ineficiente

+0

Mikko Hellsing (desarrollador SORL-miniatura) dijo que tenía que instatiate SORL-miniatura con un base_url, pero no he podido para encontrar cualquier documentación sobre cómo hacer eso. – DarwinSurvivor

Respuesta

2

Suponiendo que está utilizando Djang o 1.3 usted debe echar un vistazo a la documentación sobre Managing static files

Si todo configurado correctamente, puede incluir sus imágenes como esta:

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

Eso es lo que normalmente uso, pero necesito cambiar el tamaño de forma un tanto arbitraria (por lo tanto, el uso de sorl-thumbnail). Si resulta que no es posible utilizar sorl-thumbnail para contenido estático, es posible que me obliguen a crear varias resoluciones del archivo. – DarwinSurvivor

+2

@ DarwinSurvivor- ¿Has encontrado la respuesta a esta pregunta? También intento crear miniaturas de archivos estáticos pero no puedo resolverlo. – Clayton

+0

Al menos con easy_thumbnails esto no debería ser un problema en absoluto: http://packages.python.org/easy-thumbnails/usage.html#non-django-file-objects – arie

2

trabajé en torno a esta pasando a través de un archivo en el contexto de la plantilla desde mi vista.

Aquí es un ejemplo util función Llamé desde mi punto de vista:

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 

Probablemente se podría hacer algo similar a una etiqueta de plantilla personalizada.

3

El filtro de plantilla funciona. Pero no estoy seguro de si cada vez que se lee desde el almacenamiento. Si es así, es irrazonable ...

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

terminé secuestrar el hecho de que puede obtener de una URL, y escribí mi propia etiqueta que reemplaza el método _render en el 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) 

Luego de la plantilla:

{% with path=STATIC_URL|add:"/path/to/static/image.png" %} 
{% thumbnail path "50x50" as thumb %} 
<img src="{{ thumb.url }}" /> 
... 
No

la solución más elegante ...: -/

0

el valor por defecto o f configuración sorl THUMBNAIL_STORAGE es la misma configuración.DEFAULT_FILE_STORAGE.

Debe crear almacenamiento que utiliza STATIC_ROOT, por ejemplo, puede usar 'django.core.files.storage.FileSystemStorage' y cree una instancia con ubicación = settings.STATIC_ROOT y base_url = settings.STATIC_URL

Solo THUMBNAIL_STORAGE establecido en la configuración de un 'MyCustomFileStorage' no funcionó. Así que tuve que hacer para DEFAULT_FILE_STORAGE y funcionó.

Definir en settings.py:

DEFAULT_FILE_STORAGE = 'utils.storage.StaticFilesStorage'

utils/almacenamiento.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) 

Referencia:

https://github.com/mneuhaus/heinzel/blob/master/staticfiles/storage.py

https://docs.djangoproject.com/en/dev/ref/settings/#default-file-storage

Cuestiones relacionadas