Python django.conf.settings.TEMPLATES Examples

The following are 26 code examples for showing how to use django.conf.settings.TEMPLATES(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: GTDWeb   Author: lanbing510   File: utils.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 
Example 2
Project: GTDWeb   Author: lanbing510   File: django_1_8_0.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 [] 
Example 3
Project: bioforum   Author: reBiocoder   File: utils.py    License: MIT License 6 votes vote down vote up
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 
Example 4
Project: django-ra-erp   Author: ra-systems   File: checks.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example 5
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: utils.py    License: MIT License 6 votes vote down vote up
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 
Example 6
Project: python   Author: Yeah-Kun   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 7
Project: apm-agent-python   Author: elastic   File: django_tests.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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"]) 
Example 8
Project: openhgsenti   Author: drexly   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 9
Project: python2017   Author: bpgc-cte   File: utils.py    License: MIT License 6 votes vote down vote up
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 
Example 10
Project: GTDWeb   Author: lanbing510   File: utils.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, templates=None):
        """
        templates is an optional list of template engine definitions
        (structured like settings.TEMPLATES).
        """
        self._templates = templates
        self._engines = {} 
Example 11
Project: bioforum   Author: reBiocoder   File: utils.py    License: MIT License 5 votes vote down vote up
def __init__(self, templates=None):
        """
        templates is an optional list of template engine definitions
        (structured like settings.TEMPLATES).
        """
        self._templates = templates
        self._engines = {} 
Example 12
Project: bioforum   Author: reBiocoder   File: utils.py    License: MIT License 5 votes vote down vote up
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 
Example 13
Project: django-ra-erp   Author: ra-systems   File: checks.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 
Example 14
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: utils.py    License: MIT License 5 votes vote down vote up
def __init__(self, templates=None):
        """
        templates is an optional list of template engine definitions
        (structured like settings.TEMPLATES).
        """
        self._templates = templates
        self._engines = {} 
Example 15
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: utils.py    License: MIT License 5 votes vote down vote up
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 
Example 16
Project: python   Author: Yeah-Kun   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, templates=None):
        """
        templates is an optional list of template engine definitions
        (structured like settings.TEMPLATES).
        """
        self._templates = templates
        self._engines = {} 
Example 17
Project: python   Author: Yeah-Kun   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
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 
Example 18
Project: apm-agent-python   Author: elastic   File: django_tests.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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" 
Example 19
Project: openhgsenti   Author: drexly   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, templates=None):
        """
        templates is an optional list of template engine definitions
        (structured like settings.TEMPLATES).
        """
        self._templates = templates
        self._engines = {} 
Example 20
Project: tetre   Author: aoldoni   File: command_utils.py    License: MIT License 5 votes vote down vote up
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() 
Example 21
Project: python2017   Author: bpgc-cte   File: utils.py    License: MIT License 5 votes vote down vote up
def __init__(self, templates=None):
        """
        templates is an optional list of template engine definitions
        (structured like settings.TEMPLATES).
        """
        self._templates = templates
        self._engines = {} 
Example 22
Project: python2017   Author: bpgc-cte   File: utils.py    License: MIT License 5 votes vote down vote up
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 
Example 23
Project: django-sniplates   Author: funkybob   File: utils.py    License: MIT License 5 votes vote down vote up
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) 
Example 24
Project: tethys   Author: tethysplatform   File: tethys_gizmos.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 '' 
Example 25
Project: GTDWeb   Author: lanbing510   File: utils.py    License: GNU General Public License v2.0 4 votes vote down vote up
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 
Example 26
Project: openhgsenti   Author: drexly   File: utils.py    License: Apache License 2.0 4 votes vote down vote up
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