0

'隐式'我的意思是,在 Django 1.6 中,生成的 settings.py 中省略了一些设置(由 django-admin startproject),例如,在 settings.py 中不会有 TEMPLATE_LOADERS 放置在那里,但它实际上有默认值:

$ ./manage.py shell
>>> from django.conf import settings
>>> print settings.TEMPLATE_LOADERS
    ('django.template.loaders.filesystem.Loader',
     'django.template.loaders.app_directories.Loader')

我试过像这样更新 settings.py :

TEMPLATE_LOADERS += (
    'django.template.loaders.eggs.Loader',
)

但它将失败并出现以下错误:

NameError: name 'TEMPLATE_LOADERS' is not defined

我只是想知道是否有最佳实践将额外的模板加载器添加到默认列表中而不是这样做(重复默认加载器有点难看):

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

1 回答 1

2

您正在尝试更新未定义的变量,您应该创建或导入它。默认设置值在 django.conf.global_settings 中定义。如果将此行添加到文件的顶部,它应该可以工作:

from django.conf.global_settings import TEMPLATE_LOADERS

不确定这是否是一个好习惯,因为您可能想确切地知道您正在使用哪些设置。

默认设置的完整列表在这里:

django.conf.global_settings

这是 Django 使用用户设置覆盖默认设置的机制,其中 mod 是用户设置, global_settings 是默认设置:

# django/conf/__init__.py

def __init__(self, settings_module):
    # update this dict from global settings (but only for ALL_CAPS settings)
    for setting in dir(global_settings):
        if setting.isupper():
            setattr(self, setting, getattr(global_settings, setting))

    # store the settings module in case someone later cares
    self.SETTINGS_MODULE = settings_module

    try:
        mod = importlib.import_module(self.SETTINGS_MODULE)
    except ImportError as e:
        raise ImportError(
            "Could not import settings '%s' (Is it on sys.path? Is there an import error in the settings file?): %s"
            % (self.SETTINGS_MODULE, e)
        )

    tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS")
    self._explicit_settings = set()
    for setting in dir(mod):
        if setting.isupper():
            setting_value = getattr(mod, setting)

            if (setting in tuple_settings and
                    isinstance(setting_value, six.string_types)):
                raise ImproperlyConfigured("The %s setting must be a tuple. "
                        "Please fix your settings." % setting)
            setattr(self, setting, setting_value)
            self._explicit_settings.add(setting)
于 2014-04-12T17:10:32.480 回答