无法使用sorl-thumbnail与MEDIA_ROOT设置

时间:2015-08-10 17:02:25

标签: python django caching sorl-thumbnail django-media

从我在settings.py中定义MEDIA_ROOT的那一刻起,我无法获得sorl-thumbnail来生成带图像的缓存文件夹。在此之前,我没有设置MEDIA_ROOT并且工作正常。

请注意我正在测试DEBUG = True。

以下是我的设置:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

DEBUG = True
TEMPLATE_DEBUG = DEBUG

INSTALLED_APPS = (
    'django.contrib.sites',
    'grappelli',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'djangobower',
    'pipeline',
    'sorl.thumbnail',
    'django_countries',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    # Local apps
    ...

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_STORAGE = 'pipeline.storage.PipelineStorage'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

THUMBNAIL_DEBUG = DEBUG
THUMBNAIL_PREFIX = 'cache/'

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'pipeline.finders.PipelineFinder',
)

# TODO : use redis in prod
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'cache',
    }
}

我的home.html文件包含:

{% extends 'base.html' %}

{% load static i18n thumbnail %}

{% static 'main/img/business_man_in_the_mirror.jpg' as business_man_in_the_mirror %}
{{ business_man_in_the_mirror }}
{% thumbnail business_man_in_the_mirror|slice:"1:" "x300" as im %}
    {{ im.url }}
    <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"
         alt="{% trans "Homme d'affaire se regardant dans le miroir" %}"
         class="center-block img-responsive">
{% endthumbnail %}

{{business_man_in_the_mirror}}打印&#34; /static/main/img/business_man_in_the_mirror.jpg"。

{{im.url}}打印&#34; /media/cache/d0/38/d038a3e64b2c7d070088e368ee881027.jpg"

到目前为止一切顺利。但是从未创建MEDIA_ROOT中的缓存文件夹。 MEDIA_ROOT甚至有777。 我没有看到./manage.py runserver -v 3的任何错误。 所以我的网页中缺少图像。

runserver日志显示以下内容:

[10/Aug/2015 18:47:47]"GET /media/cache/d0/38/d038a3e64b2c7d070088e368ee881027.jpg HTTP/1.1" 404 2870

http://localhost:8000/static/main/img/business_man_in_the_mirror.jpg确实向我展示了图片。

我尝试./manage.py thumbnail cleanup./manage.py thumbnail clear,但没有效果。 我也尝试删除DB中的kvstore表和缓存表,什么都没改变。 我在缓存中有5行,但kvstore表中没有任何内容。

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

请看一下这个问题:How to thumbnail static files?。我一开始没有看到它,但它给出了我的问题的答案。

所以,如果你做的与我相同,例如缩略图没有设置MEDIA_ROOT的静态图像,然后设置MEDIA_ROOT,这就是为什么它不再起作用了。

使用sorl-thumbnail提供静态文件不能用于静态图像的abspath。相反,请使用http://localhost:8000或www.example.com等内容将模板中的STATIC_URL用作前缀。

我不知道这种做法在生产环境中的影响,但是它在我当地的Django项目的根目录上创建了一个cache文件夹,这对我来说并不开心。我暂时选择不使用缩略图作为静态图像。