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 File: tests.py    From djongo with 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 #2
Source File: tests.py    From djongo with 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 #3
Source File: test_decorators.py    From djongo with 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 File: test_html_renderer.py    From DjangoRestMultipleModels with 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 #5
Source File: test_jinja2.py    From wagtail with 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 #6
Source File: test_decorators.py    From djongo with 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 File: tests.py    From djongo with 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 File: tests.py    From djongo with 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 File: test_response.py    From djongo with 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) 
Example #10
Source File: views.py    From djongo with 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 #11
Source File: views.py    From djongo with 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 #12
Source File: urls.py    From djongo with 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 #13
Source File: urls.py    From djongo with 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 #14
Source File: tests.py    From djongo with 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 #15
Source File: test_response.py    From djongo with 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 #16
Source File: renderers.py    From Dailyfresh-B2C with 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 #17
Source File: middleware.py    From djongo with 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 #18
Source File: views.py    From djongo with 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 #19
Source File: urls.py    From djongo with 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 #20
Source File: urls.py    From djongo with 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 #21
Source File: tests.py    From djongo with 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 #22
Source File: test_templates.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        super().setUp()
        self.engine = engines['jinja2'] 
Example #23
Source File: __init__.py    From templated-docs with 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 #24
Source File: utils.py    From wagtail-tag-manager with 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 #25
Source File: api.py    From django-cachalot with 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 #26
Source File: utils.py    From wagtail-personalisation with 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 #27
Source File: tests.py    From django-tex with 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 #28
Source File: test_jinja2.py    From wagtail with 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 #29
Source File: middleware.py    From djongo with 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 #30
Source File: test_jinja2.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.engine = engines['jinja2']