Python django.template.backends.django.DjangoTemplates() Examples

The following are 23 code examples of django.template.backends.django.DjangoTemplates(). 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 also want to check out all available functions/classes of the module django.template.backends.django , or try the search function .
Example #1
Source File: engine.py    From bioforum with MIT License 6 votes vote down vote up
def get_default():
        """
        Return the first DjangoTemplates backend that's configured, or raise
        ImproperlyConfigured if none are configured.

        This is required for preserving historical APIs that rely on a
        globally available, implicitly configured engine such as:

        >>> from django.template import Context, Template
        >>> template = Template("Hello {{ name }}!")
        >>> context = Context({'name': "world"})
        >>> template.render(context)
        'Hello world!'
        """
        # Since Engine is imported in django.template and since
        # DjangoTemplates is a wrapper around this Engine class,
        # local imports are required to avoid import loops.
        from django.template import engines
        from django.template.backends.django import DjangoTemplates
        for engine in engines.all():
            if isinstance(engine, DjangoTemplates):
                return engine.engine
        raise ImproperlyConfigured('No DjangoTemplates backend is configured.') 
Example #2
Source File: engine.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def get_default():
        """
        Return the first DjangoTemplates backend that's configured, or raise
        ImproperlyConfigured if none are configured.

        This is required for preserving historical APIs that rely on a
        globally available, implicitly configured engine such as:

        >>> from django.template import Context, Template
        >>> template = Template("Hello {{ name }}!")
        >>> context = Context({'name': "world"})
        >>> template.render(context)
        'Hello world!'
        """
        # Since Engine is imported in django.template and since
        # DjangoTemplates is a wrapper around this Engine class,
        # local imports are required to avoid import loops.
        from django.template import engines
        from django.template.backends.django import DjangoTemplates
        for engine in engines.all():
            if isinstance(engine, DjangoTemplates):
                return engine.engine
        raise ImproperlyConfigured('No DjangoTemplates backend is configured.') 
Example #3
Source File: test_django.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_builtins_discovery(self):
        engine = DjangoTemplates({
            'DIRS': [],
            'APP_DIRS': False,
            'NAME': 'django',
            'OPTIONS': {
                'builtins': ['template_backends.apps.good.templatetags.good_tags'],
            },
        })

        self.assertEqual(
            engine.engine.builtins, [
                'django.template.defaulttags',
                'django.template.defaultfilters',
                'django.template.loader_tags',
                'template_backends.apps.good.templatetags.good_tags',
            ]
        ) 
Example #4
Source File: test_django.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_context_has_priority_over_template_context_processors(self):
        # See ticket #23789.
        engine = DjangoTemplates({
            'DIRS': [],
            'APP_DIRS': False,
            'NAME': 'django',
            'OPTIONS': {
                'context_processors': [test_processor_name],
            },
        })

        template = engine.from_string('{{ processors }}')
        request = RequestFactory().get('/')

        # Context processors run
        content = template.render({}, request)
        self.assertEqual(content, 'yes')

        # Context overrides context processors
        content = template.render({'processors': 'no'}, request)
        self.assertEqual(content, 'no') 
Example #5
Source File: test_django.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_render_requires_dict(self):
        """django.Template.render() requires a dict."""
        engine = DjangoTemplates({
            'DIRS': [],
            'APP_DIRS': False,
            'NAME': 'django',
            'OPTIONS': {},
        })
        template = engine.from_string('')
        context = Context()
        request_context = RequestContext(RequestFactory().get('/'), {})
        msg = 'context must be a dict rather than Context.'
        with self.assertRaisesMessage(TypeError, msg):
            template.render(context)
        msg = 'context must be a dict rather than RequestContext.'
        with self.assertRaisesMessage(TypeError, msg):
            template.render(request_context) 
Example #6
Source File: test_django.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_render_requires_dict(self):
        """django.Template.render() requires a dict."""
        engine = DjangoTemplates({
            'DIRS': [],
            'APP_DIRS': False,
            'NAME': 'django',
            'OPTIONS': {},
        })
        template = engine.from_string('')
        context = Context()
        request_context = RequestContext(self.request_factory.get('/'), {})
        msg = 'context must be a dict rather than Context.'
        with self.assertRaisesMessage(TypeError, msg):
            template.render(context)
        msg = 'context must be a dict rather than RequestContext.'
        with self.assertRaisesMessage(TypeError, msg):
            template.render(request_context) 
Example #7
Source File: test_django.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_context_has_priority_over_template_context_processors(self):
        # See ticket #23789.
        engine = DjangoTemplates({
            'DIRS': [],
            'APP_DIRS': False,
            'NAME': 'django',
            'OPTIONS': {
                'context_processors': [test_processor_name],
            },
        })

        template = engine.from_string('{{ processors }}')
        request = self.request_factory.get('/')

        # Context processors run
        content = template.render({}, request)
        self.assertEqual(content, 'yes')

        # Context overrides context processors
        content = template.render({'processors': 'no'}, request)
        self.assertEqual(content, 'no') 
Example #8
Source File: test_django.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_builtins_discovery(self):
        engine = DjangoTemplates({
            'DIRS': [],
            'APP_DIRS': False,
            'NAME': 'django',
            'OPTIONS': {
                'builtins': ['template_backends.apps.good.templatetags.good_tags'],
            },
        })

        self.assertEqual(
            engine.engine.builtins, [
                'django.template.defaulttags',
                'django.template.defaultfilters',
                'django.template.loader_tags',
                'template_backends.apps.good.templatetags.good_tags',
            ]
        ) 
Example #9
Source File: test_django.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_non_debug_default_template_loaders(self):
        engine = DjangoTemplates({'DIRS': [], 'APP_DIRS': True, 'NAME': 'django', 'OPTIONS': {}})
        self.assertEqual(engine.engine.loaders, [('django.template.loaders.cached.Loader', self.default_loaders)]) 
Example #10
Source File: engine.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_default():
        """
        When only one DjangoTemplates backend is configured, returns it.

        Raises ImproperlyConfigured otherwise.

        This is required for preserving historical APIs that rely on a
        globally available, implicitly configured engine such as:

        >>> from django.template import Context, Template
        >>> template = Template("Hello {{ name }}!")
        >>> context = Context({'name': "world"})
        >>> template.render(context)
        'Hello world!'
        """
        # Since Engine is imported in django.template and since
        # DjangoTemplates is a wrapper around this Engine class,
        # local imports are required to avoid import loops.
        from django.template import engines
        from django.template.backends.django import DjangoTemplates
        django_engines = [engine for engine in engines.all()
                          if isinstance(engine, DjangoTemplates)]
        if len(django_engines) == 1:
            # Unwrap the Engine instance inside DjangoTemplates
            return django_engines[0].engine
        elif len(django_engines) == 0:
            raise ImproperlyConfigured(
                "No DjangoTemplates backend is configured.")
        else:
            raise ImproperlyConfigured(
                "Several DjangoTemplates backends are configured. "
                "You must select one explicitly.") 
Example #11
Source File: test_django.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_autoescape_default(self):
        templates = [{
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
        }]
        engines = EngineHandler(templates=templates)
        self.assertEqual(
            engines['django'].from_string('Hello, {{ name }}').render({'name': 'Bob & Jim'}),
            'Hello, Bob & Jim'
        ) 
Example #12
Source File: test_django.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_autoescape_off(self):
        templates = [{
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'OPTIONS': {'autoescape': False},
        }]
        engines = EngineHandler(templates=templates)
        self.assertEqual(
            engines['django'].from_string('Hello, {{ name }}').render({'name': 'Bob & Jim'}),
            'Hello, Bob & Jim'
        ) 
Example #13
Source File: test_django.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_templatetag_discovery_import_error(self):
        """
        Import errors in tag modules should be reraised with a helpful message.
        """
        with self.assertRaisesMessage(
            InvalidTemplateLibrary,
            "ImportError raised when trying to load "
            "'template_backends.apps.importerror.templatetags.broken_tags'"
        ):
            DjangoTemplates({
                'DIRS': [],
                'APP_DIRS': False,
                'NAME': 'django',
                'OPTIONS': {},
            }) 
Example #14
Source File: test_django.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_debug_default_template_loaders(self):
        engine = DjangoTemplates({'DIRS': [], 'APP_DIRS': True, 'NAME': 'django', 'OPTIONS': {}})
        self.assertEqual(engine.engine.loaders, self.default_loaders) 
Example #15
Source File: test_django.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_non_debug_default_template_loaders(self):
        engine = DjangoTemplates({'DIRS': [], 'APP_DIRS': True, 'NAME': 'django', 'OPTIONS': {}})
        self.assertEqual(engine.engine.loaders, [('django.template.loaders.cached.Loader', self.default_loaders)]) 
Example #16
Source File: test_django.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_autoescape_default(self):
        templates = [{
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
        }]
        engines = EngineHandler(templates=templates)
        self.assertEqual(
            engines['django'].from_string('Hello, {{ name }}').render({'name': 'Bob & Jim'}),
            'Hello, Bob & Jim'
        ) 
Example #17
Source File: test_django.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_templatetag_discovery_import_error(self):
        """
        Import errors in tag modules should be reraised with a helpful message.
        """
        with self.assertRaisesMessage(
            InvalidTemplateLibrary,
            "ImportError raised when trying to load "
            "'template_backends.apps.importerror.templatetags.broken_tags'"
        ):
            DjangoTemplates({
                'DIRS': [],
                'APP_DIRS': False,
                'NAME': 'django',
                'OPTIONS': {},
            }) 
Example #18
Source File: test_django.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_templatetag_discovery(self):
        engine = DjangoTemplates({
            'DIRS': [],
            'APP_DIRS': False,
            'NAME': 'django',
            'OPTIONS': {
                'libraries': {
                    'alternate': 'template_backends.apps.good.templatetags.good_tags',
                    'override': 'template_backends.apps.good.templatetags.good_tags',
                },
            },
        })

        # libraries are discovered from installed applications
        self.assertEqual(
            engine.engine.libraries['good_tags'],
            'template_backends.apps.good.templatetags.good_tags',
        )
        self.assertEqual(
            engine.engine.libraries['subpackage.tags'],
            'template_backends.apps.good.templatetags.subpackage.tags',
        )
        # libraries are discovered from django.templatetags
        self.assertEqual(
            engine.engine.libraries['static'],
            'django.templatetags.static',
        )
        # libraries passed in OPTIONS are registered
        self.assertEqual(
            engine.engine.libraries['alternate'],
            'template_backends.apps.good.templatetags.good_tags',
        )
        # libraries passed in OPTIONS take precedence over discovered ones
        self.assertEqual(
            engine.engine.libraries['override'],
            'template_backends.apps.good.templatetags.good_tags',
        ) 
Example #19
Source File: engine.py    From python2017 with MIT License 5 votes vote down vote up
def get_default():
        """
        When only one DjangoTemplates backend is configured, returns it.

        Raises ImproperlyConfigured otherwise.

        This is required for preserving historical APIs that rely on a
        globally available, implicitly configured engine such as:

        >>> from django.template import Context, Template
        >>> template = Template("Hello {{ name }}!")
        >>> context = Context({'name': "world"})
        >>> template.render(context)
        'Hello world!'
        """
        # Since Engine is imported in django.template and since
        # DjangoTemplates is a wrapper around this Engine class,
        # local imports are required to avoid import loops.
        from django.template import engines
        from django.template.backends.django import DjangoTemplates
        django_engines = [engine for engine in engines.all()
                          if isinstance(engine, DjangoTemplates)]
        if len(django_engines) == 1:
            # Unwrap the Engine instance inside DjangoTemplates
            return django_engines[0].engine
        elif len(django_engines) == 0:
            raise ImproperlyConfigured(
                "No DjangoTemplates backend is configured.")
        else:
            raise ImproperlyConfigured(
                "Several DjangoTemplates backends are configured. "
                "You must select one explicitly.") 
Example #20
Source File: request_history.py    From django-debug-toolbar-request-history with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_template():
    if this_module.template is None:
        template_path = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            'request_history.html'
        )
        with open(template_path) as template_file:
            this_module.template = Template(
                template_file.read(),
                engine=DjangoTemplates({'NAME': 'rh', 'DIRS': [], 'APP_DIRS': False, 'OPTIONS': {}}).engine
        )
    return this_module.template 
Example #21
Source File: engine.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_default():
        """
        When only one DjangoTemplates backend is configured, returns it.

        Raises ImproperlyConfigured otherwise.

        This is required for preserving historical APIs that rely on a
        globally available, implicitly configured engine such as:

        >>> from django.template import Context, Template
        >>> template = Template("Hello {{ name }}!")
        >>> context = Context({'name': "world"})
        >>> template.render(context)
        'Hello world!'
        """
        # Since Engine is imported in django.template and since
        # DjangoTemplates is a wrapper around this Engine class,
        # local imports are required to avoid import loops.
        from django.template import engines
        from django.template.backends.django import DjangoTemplates
        django_engines = [engine for engine in engines.all()
                          if isinstance(engine, DjangoTemplates)]
        if len(django_engines) == 1:
            # Unwrap the Engine instance inside DjangoTemplates
            return django_engines[0].engine
        elif len(django_engines) == 0:
            raise ImproperlyConfigured(
                "No DjangoTemplates backend is configured.")
        else:
            raise ImproperlyConfigured(
                "Several DjangoTemplates backends are configured. "
                "You must select one explicitly.") 
Example #22
Source File: apps.py    From django-user-messages with MIT License 5 votes vote down vote up
def check_context_processors(app_configs, **kwargs):
    errors = []

    if VERSION < (2, 2):
        # The admin.E404 check has been introduced in the Django 2.2 cycle.
        return errors

    for engine in engines.all():
        if isinstance(engine, DjangoTemplates):
            django_templates_instance = engine.engine
            break
    else:
        django_templates_instance = None

    if django_templates_instance:
        if (
            "django.contrib.messages.context_processors.messages"
            not in django_templates_instance.context_processors
            and "admin.E404" not in settings.SILENCED_SYSTEM_CHECKS
        ):
            errors.append(
                checks.Error(
                    "If using 'user_messages.context_processors.messages'"
                    " instead of the official messages context processor"
                    " you have to add 'admin.E404' to SILENCED_SYSTEM_CHECKS.",
                    id="user_messages.E001",
                )
            )

    return errors 
Example #23
Source File: engine.py    From python with Apache License 2.0 5 votes vote down vote up
def get_default():
        """
        When only one DjangoTemplates backend is configured, returns it.

        Raises ImproperlyConfigured otherwise.

        This is required for preserving historical APIs that rely on a
        globally available, implicitly configured engine such as:

        >>> from django.template import Context, Template
        >>> template = Template("Hello {{ name }}!")
        >>> context = Context({'name': "world"})
        >>> template.render(context)
        'Hello world!'
        """
        # Since Engine is imported in django.template and since
        # DjangoTemplates is a wrapper around this Engine class,
        # local imports are required to avoid import loops.
        from django.template import engines
        from django.template.backends.django import DjangoTemplates
        django_engines = [engine for engine in engines.all()
                          if isinstance(engine, DjangoTemplates)]
        if len(django_engines) == 1:
            # Unwrap the Engine instance inside DjangoTemplates
            return django_engines[0].engine
        elif len(django_engines) == 0:
            raise ImproperlyConfigured(
                "No DjangoTemplates backend is configured.")
        else:
            raise ImproperlyConfigured(
                "Several DjangoTemplates backends are configured. "
                "You must select one explicitly.")