當前位置: 首頁>>代碼示例>>Python>>正文


Python settings.TEMPLATES屬性代碼示例

本文整理匯總了Python中django.conf.settings.TEMPLATES屬性的典型用法代碼示例。如果您正苦於以下問題:Python settings.TEMPLATES屬性的具體用法?Python settings.TEMPLATES怎麽用?Python settings.TEMPLATES使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在django.conf.settings的用法示例。


在下文中一共展示了settings.TEMPLATES屬性的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __getitem__

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import TEMPLATES [as 別名]
def __getitem__(self, alias):
        try:
            return self._engines[alias]
        except KeyError:
            try:
                params = self.templates[alias]
            except KeyError:
                raise InvalidTemplateEngineError(
                    "Could not find config for '{}' "
                    "in settings.TEMPLATES".format(alias))

            # If importing or initializing the backend raises an exception,
            # self._engines[alias] isn't set and this code may get executed
            # again, so we must preserve the original params. See #24265.
            params = params.copy()
            backend = params.pop('BACKEND')
            engine_cls = import_string(backend)
            engine = engine_cls(params)

            self._engines[alias] = engine
            return engine 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:23,代碼來源:utils.py

示例2: check_duplicate_template_settings

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import TEMPLATES [as 別名]
def check_duplicate_template_settings(app_configs, **kwargs):
    if settings.TEMPLATES:
        values = [
            'TEMPLATE_DIRS',
            'ALLOWED_INCLUDE_ROOTS',
            'TEMPLATE_CONTEXT_PROCESSORS',
            'TEMPLATE_DEBUG',
            'TEMPLATE_LOADERS',
            'TEMPLATE_STRING_IF_INVALID',
        ]
        duplicates = [
            value for value in values
            if getattr(settings, value) != getattr(global_settings, value)
        ]
        if duplicates:
            return [Warning(
                "The standalone TEMPLATE_* settings were deprecated in Django "
                "1.8 and the TEMPLATES dictionary takes precedence. You must "
                "put the values of the following settings into your default "
                "TEMPLATES dict: %s." % ", ".join(duplicates),
                id='1_8.W001',
            )]
    return [] 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:25,代碼來源:django_1_8_0.py

示例3: check_initial_settings

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import TEMPLATES [as 別名]
def check_initial_settings(app_configs, **kwargs):
    errors = []
    if 'django.template.context_processors.i18n' not in settings.TEMPLATES[0]['OPTIONS']['context_processors']:
        errors.append(
            Error('django.template.context_processors.i18n is missing',
                  hint='Add "django.template.context_processors.i18n" to context_processors',
                  obj='settings',
                  id='ra.E003',
                  )
        )
    if 'django.template.context_processors.static' not in settings.TEMPLATES[0]['OPTIONS']['context_processors']:
        errors.append(
            Error('django.template.context_processors.static is missing',
                  hint='Add "django.template.context_processors.static" to context_processors',
                  obj='settings',
                  id='ra.E003',
                  )
        )

    return errors 
開發者ID:ra-systems,項目名稱:django-ra-erp,代碼行數:22,代碼來源:checks.py

示例4: test_rum_tracing_context_processor

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import TEMPLATES [as 別名]
def test_rum_tracing_context_processor(client, django_elasticapm_client):
    with override_settings(
        TEMPLATES=[
            {
                "BACKEND": "django.template.backends.django.DjangoTemplates",
                "DIRS": [BASE_TEMPLATE_DIR],
                "OPTIONS": {
                    "context_processors": [
                        "django.contrib.auth.context_processors.auth",
                        "elasticapm.contrib.django.context_processors.rum_tracing",
                    ],
                    "loaders": ["django.template.loaders.filesystem.Loader"],
                    "debug": False,
                },
            }
        ],
        **middleware_setting(django.VERSION, ["elasticapm.contrib.django.middleware.TracingMiddleware"])
    ):
        response = client.get(reverse("render-heavy-template"))
        transactions = django_elasticapm_client.events[TRANSACTION]
        assert response.context["apm"]["trace_id"] == transactions[0]["trace_id"]
        assert response.context["apm"]["is_sampled"]
        assert response.context["apm"]["is_sampled_js"] == "true"
        assert callable(response.context["apm"]["span_id"]) 
開發者ID:elastic,項目名稱:apm-agent-python,代碼行數:26,代碼來源:django_tests.py

示例5: __init__

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import TEMPLATES [as 別名]
def __init__(self, templates=None):
        """
        templates is an optional list of template engine definitions
        (structured like settings.TEMPLATES).
        """
        self._templates = templates
        self._engines = {} 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:9,代碼來源:utils.py

示例6: templates

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import TEMPLATES [as 別名]
def templates(self):
        if self._templates is None:
            self._templates = settings.TEMPLATES

        templates = OrderedDict()
        backend_names = []
        for tpl in self._templates:
            tpl = tpl.copy()
            try:
                # This will raise an exception if 'BACKEND' doesn't exist or
                # isn't a string containing at least one dot.
                default_name = tpl['BACKEND'].rsplit('.', 2)[-2]
            except Exception:
                invalid_backend = tpl.get('BACKEND', '<not defined>')
                raise ImproperlyConfigured(
                    "Invalid BACKEND for a template engine: {}. Check "
                    "your TEMPLATES setting.".format(invalid_backend))

            tpl.setdefault('NAME', default_name)
            tpl.setdefault('DIRS', [])
            tpl.setdefault('APP_DIRS', False)
            tpl.setdefault('OPTIONS', {})

            templates[tpl['NAME']] = tpl
            backend_names.append(tpl['NAME'])

        counts = Counter(backend_names)
        duplicates = [alias for alias, count in counts.most_common() if count > 1]
        if duplicates:
            raise ImproperlyConfigured(
                "Template engine aliases aren't unique, duplicates: {}. "
                "Set a unique NAME for each engine in settings.TEMPLATES."
                .format(", ".join(duplicates)))

        return templates 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:37,代碼來源:utils.py

示例7: check_ra_settings

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import TEMPLATES [as 別名]
def check_ra_settings(app_configs, **kwargs):
    errors = []
    if 'ra.base.context_processors.global_info' not in settings.TEMPLATES[0]['OPTIONS']['context_processors']:
        errors.append(
            Error(
                'context ra.base.context_processors.global_info is missing',
                hint="add ra.base.context_processors.global_info to context_processor",
                obj='settings',
                id='RA.E002',
            )
        )
    return errors 
開發者ID:ra-systems,項目名稱:django-ra-erp,代碼行數:14,代碼來源:checks.py

示例8: templates

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import TEMPLATES [as 別名]
def templates(self):
        if self._templates is None:
            self._templates = settings.TEMPLATES

        templates = OrderedDict()
        backend_names = []
        for tpl in self._templates:
            try:
                # This will raise an exception if 'BACKEND' doesn't exist or
                # isn't a string containing at least one dot.
                default_name = tpl['BACKEND'].rsplit('.', 2)[-2]
            except Exception:
                invalid_backend = tpl.get('BACKEND', '<not defined>')
                raise ImproperlyConfigured(
                    "Invalid BACKEND for a template engine: {}. Check "
                    "your TEMPLATES setting.".format(invalid_backend))

            tpl = {
                'NAME': default_name,
                'DIRS': [],
                'APP_DIRS': False,
                'OPTIONS': {},
                **tpl,
            }

            templates[tpl['NAME']] = tpl
            backend_names.append(tpl['NAME'])

        counts = Counter(backend_names)
        duplicates = [alias for alias, count in counts.most_common() if count > 1]
        if duplicates:
            raise ImproperlyConfigured(
                "Template engine aliases aren't unique, duplicates: {}. "
                "Set a unique NAME for each engine in settings.TEMPLATES."
                .format(", ".join(duplicates)))

        return templates 
開發者ID:PacktPublishing,項目名稱:Hands-On-Application-Development-with-PyCharm,代碼行數:39,代碼來源:utils.py

示例9: test_stacktraces_have_templates

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import TEMPLATES [as 別名]
def test_stacktraces_have_templates(client, django_elasticapm_client):
    # only Django 1.9+ have the necessary information stored on Node/Template
    # instances when TEMPLATE_DEBUG = False

    TEMPLATE_DEBUG = django.VERSION < (1, 9)

    TEMPLATES_copy = deepcopy(settings.TEMPLATES)
    TEMPLATES_copy[0]["OPTIONS"]["debug"] = TEMPLATE_DEBUG
    with override_settings(
        TEMPLATE_DEBUG=TEMPLATE_DEBUG,
        TEMPLATES=TEMPLATES_copy,
        **middleware_setting(django.VERSION, ["elasticapm.contrib.django.middleware.TracingMiddleware"])
    ):
        resp = client.get(reverse("render-heavy-template"))
    assert resp.status_code == 200

    transactions = django_elasticapm_client.events[TRANSACTION]
    assert len(transactions) == 1
    transaction = transactions[0]
    assert transaction["result"] == "HTTP 2xx"
    spans = django_elasticapm_client.events[SPAN]
    assert len(spans) == 2, [t["name"] for t in spans]

    expected_names = {"list_users.html", "something_expensive"}

    assert {t["name"] for t in spans} == expected_names

    assert spans[0]["name"] == "something_expensive"

    # Find the template
    for frame in spans[0]["stacktrace"]:
        if frame["lineno"] == 4 and frame["filename"].endswith(
            os.path.join("django", "testapp", "templates", "list_users.html")
        ):
            break
    else:
        assert False is True, "Template was not found" 
開發者ID:elastic,項目名稱:apm-agent-python,代碼行數:39,代碼來源:django_tests.py

示例10: setup_django_template_system

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import TEMPLATES [as 別名]
def setup_django_template_system():
    """Initialises the Django templating system as to be used standalone.
    """
    settings.configure()
    settings.TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates'
        }
    ]
    django.setup() 
開發者ID:aoldoni,項目名稱:tetre,代碼行數:12,代碼來源:command_utils.py

示例11: template_dirs

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import TEMPLATES [as 別名]
def template_dirs(*relative_dirs):
    """
    Convenient decorator to specify the template path.
    """
    # copy the original setting
    TEMPLATES = copy.deepcopy(settings.TEMPLATES)
    for tpl_cfg in TEMPLATES:
        tpl_cfg['DIRS'] = [template_path(rel_dir) for rel_dir in relative_dirs]
    return override_settings(TEMPLATES=TEMPLATES) 
開發者ID:funkybob,項目名稱:django-sniplates,代碼行數:11,代碼來源:utils.py

示例12: render

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import TEMPLATES [as 別名]
def render(self, context):
        resolved_options = template.Variable(self.options).resolve(context)

        try:
            if self.gizmo_name is None or self.gizmo_name not in GIZMO_NAME_MAP:
                if hasattr(resolved_options, GIZMO_NAME_PROPERTY):
                    self._load_gizmo_name(resolved_options.gizmo_name)
                else:
                    raise TemplateSyntaxError('A valid gizmo name is required for this input format.')

            self._load_gizmos_rendered(context)

            # Derive path to gizmo template
            if self.gizmo_name not in EXTENSION_PATH_MAP:
                # Determine path to gizmo template
                gizmo_templates_root = os.path.join('tethys_gizmos', 'gizmos')

            else:
                gizmo_templates_root = os.path.join(EXTENSION_PATH_MAP[self.gizmo_name], 'templates', 'gizmos')

            gizmo_file_name = '{0}.html'.format(self.gizmo_name)
            template_name = os.path.join(gizmo_templates_root, gizmo_file_name)

            # reset gizmo_name in case Node is rendered with different options
            self._load_gizmo_name(None)

            # Retrieve the gizmo template and render
            t = get_template(template_name)
            return t.render(resolved_options)

        except Exception:
            if hasattr(settings, 'TEMPLATES'):
                for template_settings in settings.TEMPLATES:
                    if 'OPTIONS' in template_settings \
                            and 'debug' in template_settings['OPTIONS'] \
                            and template_settings['OPTIONS']['debug']:
                        raise
            return '' 
開發者ID:tethysplatform,項目名稱:tethys,代碼行數:40,代碼來源:tethys_gizmos.py

示例13: templates

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import TEMPLATES [as 別名]
def templates(self):
        if self._templates is None:
            self._templates = settings.TEMPLATES

        if not self._templates:
            warnings.warn(
                "You haven't defined a TEMPLATES setting. You must do so "
                "before upgrading to Django 1.10. Otherwise Django will be "
                "unable to load templates.", RemovedInDjango110Warning)
            self._templates = [
                {
                    'BACKEND': 'django.template.backends.django.DjangoTemplates',
                    'DIRS': settings.TEMPLATE_DIRS,
                    'OPTIONS': {
                        'allowed_include_roots': settings.ALLOWED_INCLUDE_ROOTS,
                        'context_processors': settings.TEMPLATE_CONTEXT_PROCESSORS,
                        'debug': settings.TEMPLATE_DEBUG,
                        'loaders': settings.TEMPLATE_LOADERS,
                        'string_if_invalid': settings.TEMPLATE_STRING_IF_INVALID,
                    },
                },
            ]

        templates = OrderedDict()
        backend_names = []
        for tpl in self._templates:
            tpl = tpl.copy()
            try:
                # This will raise an exception if 'BACKEND' doesn't exist or
                # isn't a string containing at least one dot.
                default_name = tpl['BACKEND'].rsplit('.', 2)[-2]
            except Exception:
                invalid_backend = tpl.get('BACKEND', '<not defined>')
                raise ImproperlyConfigured(
                    "Invalid BACKEND for a template engine: {}. Check "
                    "your TEMPLATES setting.".format(invalid_backend))

            tpl.setdefault('NAME', default_name)
            tpl.setdefault('DIRS', [])
            tpl.setdefault('APP_DIRS', False)
            tpl.setdefault('OPTIONS', {})

            templates[tpl['NAME']] = tpl
            backend_names.append(tpl['NAME'])

        counts = Counter(backend_names)
        duplicates = [alias for alias, count in counts.most_common() if count > 1]
        if duplicates:
            raise ImproperlyConfigured(
                "Template engine aliases aren't unique, duplicates: {}. "
                "Set a unique NAME for each engine in settings.TEMPLATES."
                .format(", ".join(duplicates)))

        return templates 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:56,代碼來源:utils.py


注:本文中的django.conf.settings.TEMPLATES屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。