需要帮助:django.contrib.staticfiles.finders.find

2 投票
2 回答
5422 浏览
提问于 2025-04-16 14:48

我有一个Django项目的文件结构:

project_folder/
    app_folder/
        static/
           folder1/
               file1
        templates/
        ...
    compressor -> (symlink to django_compressor app with my modifications)
    __init__.py
    manage.py
    settings.py
    urls.py

在我修改的django_compressor中的模板标签里,我调用了一个类,这个类做了以下事情:

class StorageMixin(object):
    from django import VERSION as DJANGO_VERSION
    if DJANGO_VERSION[:2] >= (1, 3):
        from django.contrib.staticfiles.finders import find as _django_find
        def _find_file_path(self, path):
            return self._django_find(path)
    else:
        def _find_file_path(self, path):
            static_roots = getattr(settings, 'STATIC_ROOTS', []) + [settings.COMPRESS_ROOT]
            for root in static_roots:
                filename = os.path.join(root, basename)
                if os.path.exists(filename):
                    return filename
            return None

所以,如果Django是新版本,它会尝试使用静态文件查找器;如果不是,它就会通过STATIC_ROOTS配置变量模拟基本的查找器。

最后,我的问题是:根据上面的文件夹结构,我把"folder1/file1"传给finders.find方法,而我的设置是:

INSTALLED_APPS = (

    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'compressor',
    'app_folder',
)

还有

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

结果我从find调用中得到了None

有没有什么想法?

更新:更奇怪的细节是,我运行了

python manage.py shell

然后做了

from django.contrib.staticfiles.finders import find
find("folder1/file1")

结果却得到了正确的结果……

2 个回答

0

我在新网站上使用静态文件,花了一些时间才设置好。你的settings.py文件里有类似的内容吗?

另外,可以看看这个链接:Django静态文件应用帮助

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/static/"
STATICFILES_ROOT =  '/path/to/my/site/static/'
STATIC_ROOT = STATICFILES_ROOT

# URL that handles the static files served from STATICFILES_ROOT.
# Example: "http://static.lawrence.com/", "http://example.com/static/"
STATICFILES_URL = '/static/'
STATIC_URL = STATICFILES_URL

# URL prefix for admin media -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'

# A list of locations of additional static files
STATICFILES_DIRS = (
    ("game",      BASE_DIR + "/game/media"),
    ("sitemedia", BASE_DIR + "/templates/media/"),
)
STATIC_DIRS = STATICFILES_DIRS

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
STATIC_FINDERS= STATICFILES_FINDERS
1

答案是:要导入整个模块,而不仅仅是 find 方法。

撰写回答