Python django.template.engines() Examples

The following are 30 code examples of django.template.engines(). 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 , or try the search function .
Example #1
Source Project: DjangoRestMultipleModels   Author: MattBroach   File: test_html_renderer.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        super(TestMMVHTMLRenderer, self).setUp()

        """
        Monkeypatch get_template
        Taken from DRF Tests
        """
        self.get_template = django.template.loader.get_template

        def get_template(template_name, dirs=None):
            if template_name == 'test.html':
                return engines['django'].from_string("<html>test: {{ data }}</html>")
            raise TemplateDoesNotExist(template_name)

        def select_template(template_name_list, dirs=None, using=None):
            if template_name_list == ['test.html']:
                return engines['django'].from_string("<html>test: {{ data }}</html>")
            raise TemplateDoesNotExist(template_name_list[0])

        django.template.loader.get_template = get_template
        django.template.loader.select_template = select_template 
Example #2
Source Project: wagtail   Author: wagtail   File: test_jinja2.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):
        self.engine = engines['jinja2']

        self.image = Image.objects.create(
            title="Test image",
            file=get_test_image_file(),
        )

        # Create an image with a missing file, by deserializing fom a python object
        # (which bypasses FileField's attempt to read the file)
        self.bad_image = list(serializers.deserialize('python', [{
            'fields': {
                'title': 'missing image',
                'height': 100,
                'file': 'original_images/missing-image.jpg',
                'width': 100,
            },
            'model': 'wagtailimages.image'
        }]))[0].object
        self.bad_image.save() 
Example #3
Source Project: djongo   Author: nesdis   File: test_decorators.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_full_dec_templateresponse(self):
        """
        All methods of middleware are called for TemplateResponses in
        the right sequence.
        """
        @full_dec
        def template_response_view(request):
            template = engines['django'].from_string("Hello world")
            return TemplateResponse(request, template)

        request = self.rf.get('/')
        response = template_response_view(request)
        self.assertTrue(getattr(request, 'process_request_reached', False))
        self.assertTrue(getattr(request, 'process_view_reached', False))
        self.assertTrue(getattr(request, 'process_template_response_reached', False))
        # response must not be rendered yet.
        self.assertFalse(response._is_rendered)
        # process_response must not be called until after response is rendered,
        # otherwise some decorators like csrf_protect and gzip_page will not
        # work correctly. See #16004
        self.assertFalse(getattr(request, 'process_response_reached', False))
        response.render()
        self.assertTrue(getattr(request, 'process_response_reached', False))
        # process_response saw the rendered content
        self.assertEqual(request.process_response_content, b"Hello world") 
Example #4
Source Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_patch_vary_headers(self):
        headers = (
            # Initial vary, new headers, resulting vary.
            (None, ('Accept-Encoding',), 'Accept-Encoding'),
            ('Accept-Encoding', ('accept-encoding',), 'Accept-Encoding'),
            ('Accept-Encoding', ('ACCEPT-ENCODING',), 'Accept-Encoding'),
            ('Cookie', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
            ('Cookie, Accept-Encoding', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
            ('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
            (None, ('Accept-Encoding', 'COOKIE'), 'Accept-Encoding, COOKIE'),
            ('Cookie,     Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
            ('Cookie    ,     Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
        )
        for initial_vary, newheaders, resulting_vary in headers:
            with self.subTest(initial_vary=initial_vary, newheaders=newheaders):
                template = engines['django'].from_string("This is a test")
                response = TemplateResponse(HttpRequest(), template)
                if initial_vary is not None:
                    response['Vary'] = initial_vary
                patch_vary_headers(response, newheaders)
                self.assertEqual(response['Vary'], resulting_vary) 
Example #5
Source Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_cache_key(self):
        request = self.factory.get(self.path)
        template = engines['django'].from_string("This is a test")
        response = TemplateResponse(HttpRequest(), template)
        key_prefix = 'localprefix'
        # Expect None if no headers have been set yet.
        self.assertIsNone(get_cache_key(request))
        # Set headers to an empty list.
        learn_cache_key(request, response)

        self.assertEqual(
            get_cache_key(request),
            'views.decorators.cache.cache_page.settingsprefix.GET.'
            '58a0a05c8a5620f813686ff969c26853.d41d8cd98f00b204e9800998ecf8427e'
        )
        # A specified key_prefix is taken into account.
        learn_cache_key(request, response, key_prefix=key_prefix)
        self.assertEqual(
            get_cache_key(request, key_prefix=key_prefix),
            'views.decorators.cache.cache_page.localprefix.GET.'
            '58a0a05c8a5620f813686ff969c26853.d41d8cd98f00b204e9800998ecf8427e'
        ) 
Example #6
Source Project: djongo   Author: nesdis   File: test_decorators.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_full_dec_templateresponse(self):
        """
        All methods of middleware are called for TemplateResponses in
        the right sequence.
        """
        @full_dec
        def template_response_view(request):
            template = engines['django'].from_string("Hello world")
            return TemplateResponse(request, template)

        request = self.rf.get('/')
        response = template_response_view(request)
        self.assertTrue(getattr(request, 'process_request_reached', False))
        self.assertTrue(getattr(request, 'process_view_reached', False))
        self.assertTrue(getattr(request, 'process_template_response_reached', False))
        # response must not be rendered yet.
        self.assertFalse(response._is_rendered)
        # process_response must not be called until after response is rendered,
        # otherwise some decorators like csrf_protect and gzip_page will not
        # work correctly. See #16004
        self.assertFalse(getattr(request, 'process_response_reached', False))
        response.render()
        self.assertTrue(getattr(request, 'process_response_reached', False))
        # process_response saw the rendered content
        self.assertEqual(request.process_response_content, b"Hello world") 
Example #7
Source Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_patch_vary_headers(self):
        headers = (
            # Initial vary, new headers, resulting vary.
            (None, ('Accept-Encoding',), 'Accept-Encoding'),
            ('Accept-Encoding', ('accept-encoding',), 'Accept-Encoding'),
            ('Accept-Encoding', ('ACCEPT-ENCODING',), 'Accept-Encoding'),
            ('Cookie', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
            ('Cookie, Accept-Encoding', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
            ('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
            (None, ('Accept-Encoding', 'COOKIE'), 'Accept-Encoding, COOKIE'),
            ('Cookie,     Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
            ('Cookie    ,     Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
        )
        for initial_vary, newheaders, resulting_vary in headers:
            with self.subTest(initial_vary=initial_vary, newheaders=newheaders):
                template = engines['django'].from_string("This is a test")
                response = TemplateResponse(HttpRequest(), template)
                if initial_vary is not None:
                    response['Vary'] = initial_vary
                patch_vary_headers(response, newheaders)
                self.assertEqual(response['Vary'], resulting_vary) 
Example #8
Source Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_cache_key(self):
        request = self.factory.get(self.path)
        template = engines['django'].from_string("This is a test")
        response = TemplateResponse(HttpRequest(), template)
        key_prefix = 'localprefix'
        # Expect None if no headers have been set yet.
        self.assertIsNone(get_cache_key(request))
        # Set headers to an empty list.
        learn_cache_key(request, response)

        self.assertEqual(
            get_cache_key(request),
            'views.decorators.cache.cache_page.settingsprefix.GET.'
            '58a0a05c8a5620f813686ff969c26853.d41d8cd98f00b204e9800998ecf8427e'
        )
        # A specified key_prefix is taken into account.
        learn_cache_key(request, response, key_prefix=key_prefix)
        self.assertEqual(
            get_cache_key(request, key_prefix=key_prefix),
            'views.decorators.cache.cache_page.localprefix.GET.'
            '58a0a05c8a5620f813686ff969c26853.d41d8cd98f00b204e9800998ecf8427e'
        ) 
Example #9
Source Project: templated-docs   Author: alexmorozov   File: __init__.py    License: MIT License 5 votes vote down vote up
def _get_template_loaders():
    """
    Get all available template loaders for the Django engine.
    """
    loaders = []

    for loader_name in engines['django'].engine.loaders:
        loader = engines['django'].engine.find_template_loader(loader_name)
        if loader is not None and hasattr(loader, 'get_template_sources'):
            loaders.append(loader)
    return tuple(loaders) 
Example #10
Source Project: wagtail-tag-manager   Author: jberghoef   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render_template(value, **context):
    template = engines["django"].from_string(value)
    request = context.pop("request", None)
    return template.render(context, request) 
Example #11
Source Project: django-cachalot   Author: noripyt   File: api.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_last_invalidation_jinja2(self):
        original_timestamp = engines['jinja2'].from_string(
            "{{ timestamp }}"
        ).render({
            'timestamp': get_last_invalidation('auth.Group', 'cachalot_test'),
        })
        template = engines['jinja2'].from_string(
            "{{ get_last_invalidation('auth.Group', 'cachalot_test') }}")
        timestamp = template.render({})

        self.assertNotEqual(timestamp, '')
        self.assertNotEqual(timestamp, '0.0')
        self.assertAlmostEqual(float(timestamp), float(original_timestamp),
                               delta=0.1) 
Example #12
Source Project: wagtail-personalisation   Author: wagtail   File: utils.py    License: MIT License 5 votes vote down vote up
def render_template(value, **context):
    template = engines['django'].from_string(value)
    request = context.pop('request', None)
    return template.render(context, request) 
Example #13
Source Project: django-tex   Author: weinbusch   File: tests.py    License: MIT License 5 votes vote down vote up
def render_template(self, template_string, context={}, using='tex'):
        engine = engines[using]
        template = engine.from_string(template_string)
        return template.render(context) 
Example #14
Source Project: wagtail   Author: wagtail   File: test_jinja2.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.engine = engines['jinja2']

        self.user = get_user_model().objects.create_superuser(
            username='test',
            email='test@email.com',
            password='password'
        )
        self.homepage = Page.objects.get(id=2) 
Example #15
Source Project: wagtail   Author: wagtail   File: test_templates.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        super().setUp()
        self.engine = engines['jinja2'] 
Example #16
Source Project: wagtail   Author: wagtail   File: test_jinja2.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.engine = engines['jinja2'] 
Example #17
Source Project: wagtail   Author: wagtail   File: test_streamfield.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        super().setUp()
        self.engine = engines['jinja2'] 
Example #18
Source Project: intake   Author: codeforamerica   File: base.py    License: MIT License 5 votes vote down vote up
def COMPRESS_JINJA2_GET_ENVIRONMENT():
    from django.template import engines
    return engines["jinja"].env 
Example #19
Source Project: scout_apm_python   Author: scoutapp   File: django_app.py    License: MIT License 5 votes vote down vote up
def template(request):
    template = engines["django"].from_string(
        "Hello {% block name %}{{ name }}{% endblock %}!"
    )
    context = {"name": "World"}
    return HttpResponse(template.render(context)) 
Example #20
Source Project: scout_apm_python   Author: scoutapp   File: django_app.py    License: MIT License 5 votes vote down vote up
def template_response(request):
    template = engines["django"].from_string(
        "Hello {% block name %}{{ name }}{% endblock %}!"
    )
    context = {"name": "World"}
    return TemplateResponse(request, template, context) 
Example #21
Source Project: django-admin-colors   Author: victorfsf   File: test_templatetags.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        self.engine = engines['django'] 
Example #22
Source Project: Dailyfresh-B2C   Author: BeanWei   File: renderers.py    License: Apache License 2.0 5 votes vote down vote up
def get_exception_template(self, response):
        template_names = [name % {'status_code': response.status_code}
                          for name in self.exception_template_names]

        try:
            # Try to find an appropriate error template
            return self.resolve_template(template_names)
        except Exception:
            # Fall back to using eg '404 Not Found'
            body = '%d %s' % (response.status_code, response.status_text.title())
            template = engines['django'].from_string(body)
            return template


# Note, subclass TemplateHTMLRenderer simply for the exception behavior 
Example #23
Source Project: djongo   Author: nesdis   File: middleware.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def process_view(self, request, view_func, view_args, view_kwargs):
        template = engines['django'].from_string('Processed view {{ view }}{% for m in mw %}\n{{ m }}{% endfor %}')
        return TemplateResponse(request, template, {'mw': [self.__class__.__name__], 'view': view_func.__name__}) 
Example #24
Source Project: djongo   Author: nesdis   File: views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def template_response(request):
    template = engines['django'].from_string('template_response OK{% for m in mw %}\n{{ m }}{% endfor %}')
    return TemplateResponse(request, template, context={'mw': []}) 
Example #25
Source Project: djongo   Author: nesdis   File: views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def template_response_error(request):
    template = engines['django'].from_string('{%')
    return TemplateResponse(request, template) 
Example #26
Source Project: djongo   Author: nesdis   File: urls.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def show(request):
    template = engines['django'].from_string(TEMPLATE)
    return HttpResponse(template.render(request=request)) 
Example #27
Source Project: djongo   Author: nesdis   File: urls.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def show_template_response(request):
    template = engines['django'].from_string(TEMPLATE)
    return TemplateResponse(request, template) 
Example #28
Source Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_cache_key_with_query(self):
        request = self.factory.get(self.path, {'test': 1})
        template = engines['django'].from_string("This is a test")
        response = TemplateResponse(HttpRequest(), template)
        # Expect None if no headers have been set yet.
        self.assertIsNone(get_cache_key(request))
        # Set headers to an empty list.
        learn_cache_key(request, response)
        # The querystring is taken into account.
        self.assertEqual(
            get_cache_key(request),
            'views.decorators.cache.cache_page.settingsprefix.GET.'
            '0f1c2d56633c943073c4569d9a9502fe.d41d8cd98f00b204e9800998ecf8427e'
        ) 
Example #29
Source Project: djongo   Author: nesdis   File: test_response.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _response(self, template='foo', *args, **kwargs):
        template = engines['django'].from_string(template)
        return SimpleTemplateResponse(template, *args, **kwargs) 
Example #30
Source Project: djongo   Author: nesdis   File: test_response.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _response(self, template='foo', *args, **kwargs):
        self._request = self.factory.get('/')
        template = engines['django'].from_string(template)
        return TemplateResponse(self._request, template, *args, **kwargs)