Python django.template.Engine() Examples

The following are 30 code examples for showing how to use django.template.Engine(). 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.template , or try the search function .

Example 1
Project: GTDWeb   Author: lanbing510   File: defaults.py    License: GNU General Public License v2.0 6 votes vote down vote up
def page_not_found(request, template_name='404.html'):
    """
    Default 404 handler.

    Templates: :template:`404.html`
    Context:
        request_path
            The path of the requested URL (e.g., '/app/pages/bad_page/')
    """
    context = {'request_path': request.path}
    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None             # Django will use DEFAULT_CONTENT_TYPE
    except TemplateDoesNotExist:
        template = Engine().from_string(
            '<h1>Not Found</h1>'
            '<p>The requested URL {{ request_path }} was not found on this server.</p>')
        body = template.render(Context(context))
        content_type = 'text/html'
    return http.HttpResponseNotFound(body, content_type=content_type) 
Example 2
Project: GTDWeb   Author: lanbing510   File: static.py    License: GNU General Public License v2.0 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine().from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c = Context({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example 3
Project: bioforum   Author: reBiocoder   File: static.py    License: MIT License 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
        c = Context()
    else:
        c = {}
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c.update({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example 4
Project: DeerU   Author: gojuukaze   File: start.py    License: GNU General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        self.type = options['type']
        self.name = options['name']
        management.call_command('startapp', self.name)
        dir_name = ['management', Path('management/commands')]
        self.mk_dir(dir_name)

        if self.type == 'theme':
            dir_name = ['static', Path('static/' + self.name), 'templates', Path('templates/' + self.name)]
            self.mk_dir(dir_name)

        context = Context({
            'app_name': self.name,
            'app_camel_name': self.name[0].upper() + self.name[1:],
            'app_upper_name': self.name.upper(),
            'deeru_type': self.type
        }, autoescape=False)

        for template_name, new_file in self.get_app_templates():
            template = Engine().from_string(self.get_template_str(template_name))
            content = template.render(context)
            new_file.write_text(content) 
Example 5
Project: django-tenants   Author: django-tenants   File: test_filesystem.py    License: MIT License 6 votes vote down vote up
def setUpClass(cls):
        test_app_root = settings.TENANT_APPS_DIR
        settings.MULTITENANT_TEMPLATE_DIRS = [
            os.path.join(test_app_root, "tenants/%s/templates")
        ]

        cls.engine = Engine(
            loaders=[
                (
                    "django_tenants.template.loaders.cached.Loader",
                    ["django_tenants.template.loaders.filesystem.Loader"],
                )
            ]
        )

        super().setUpClass() 
Example 6
Project: django-tenants   Author: django-tenants   File: test_cached.py    License: MIT License 6 votes vote down vote up
def setUpClass(cls):
        test_app_root = settings.TENANT_APPS_DIR
        settings.MULTITENANT_TEMPLATE_DIRS = [
            os.path.join(test_app_root, "tenants/%s/templates")
        ]

        cls.engine = Engine(
            loaders=[
                (
                    "django_tenants.template.loaders.cached.Loader",
                    ["django_tenants.template.loaders.filesystem.Loader"],
                )
            ]
        )

        super().setUpClass() 
Example 7
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: static.py    License: MIT License 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
        c = Context()
    else:
        c = {}
    files = []
    for f in fullpath.iterdir():
        if not f.name.startswith('.'):
            url = str(f.relative_to(fullpath))
            if f.is_dir():
                url += '/'
            files.append(url)
    c.update({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example 8
Project: python   Author: Yeah-Kun   File: static.py    License: Apache License 2.0 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
        c = Context()
    else:
        c = {}
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c.update({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example 9
Project: openhgsenti   Author: drexly   File: static.py    License: Apache License 2.0 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine().from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c = Context({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example 10
Project: python2017   Author: bpgc-cte   File: static.py    License: MIT License 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
        c = Context()
    else:
        c = {}
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c.update({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example 11
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_url_reverse_view_name(self):
        """
        #19827 -- url tag should keep original strack trace when reraising
        exception.
        """
        t = Engine().from_string('{% url will_not_match %}')
        c = Context()
        try:
            t.render(c)
        except NoReverseMatch:
            tb = sys.exc_info()[2]
            depth = 0
            while tb.tb_next is not None:
                tb = tb.tb_next
                depth += 1
            self.assertGreater(depth, 5, "The traceback context was lost when reraising the traceback.") 
Example 12
Project: djongo   Author: nesdis   File: test_extends.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_recursive_multiple_loaders(self):
        engine = Engine(
            dirs=[os.path.join(RECURSIVE, 'fs')],
            loaders=[(
                'django.template.loaders.locmem.Loader', {
                    'one.html': (
                        '{% extends "one.html" %}{% block content %}{{ block.super }} locmem-one{% endblock %}'
                    ),
                    'two.html': (
                        '{% extends "two.html" %}{% block content %}{{ block.super }} locmem-two{% endblock %}'
                    ),
                    'three.html': (
                        '{% extends "three.html" %}{% block content %}{{ block.super }} locmem-three{% endblock %}'
                    ),
                }
            ), 'django.template.loaders.filesystem.Loader'],
        )
        template = engine.get_template('one.html')
        output = template.render(Context({}))
        self.assertEqual(output.strip(), 'three locmem-three two locmem-two one locmem-one') 
Example 13
Project: djongo   Author: nesdis   File: test_extends.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_unique_history_per_loader(self):
        """
        Extending should continue even if two loaders return the same
        name for a template.
        """
        engine = Engine(
            loaders=[
                ['django.template.loaders.locmem.Loader', {
                    'base.html': '{% extends "base.html" %}{% block content %}{{ block.super }} loader1{% endblock %}',
                }],
                ['django.template.loaders.locmem.Loader', {
                    'base.html': '{% block content %}loader2{% endblock %}',
                }],
            ]
        )
        template = engine.get_template('base.html')
        output = template.render(Context({}))
        self.assertEqual(output.strip(), 'loader2 loader1') 
Example 14
Project: djongo   Author: nesdis   File: test_extends.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_block_override_in_extended_included_template(self):
        """
        ExtendsNode.find_template() initializes history with self.origin
        (#28071).
        """
        engine = Engine(
            loaders=[
                ['django.template.loaders.locmem.Loader', {
                    'base.html': "{% extends 'base.html' %}{% block base %}{{ block.super }}2{% endblock %}",
                    'included.html':
                        "{% extends 'included.html' %}{% block included %}{{ block.super }}B{% endblock %}",
                }],
                ['django.template.loaders.locmem.Loader', {
                    'base.html': "{% block base %}1{% endblock %}{% include 'included.html' %}",
                    'included.html': "{% block included %}A{% endblock %}",
                }],
            ],
        )
        template = engine.get_template('base.html')
        self.assertEqual(template.render(Context({})), '12AB') 
Example 15
Project: GTDWeb   Author: lanbing510   File: i18n.py    License: GNU General Public License v2.0 5 votes vote down vote up
def render_javascript_catalog(catalog=None, plural=None):
    template = Engine().from_string(js_catalog_template)
    indent = lambda s: s.replace('\n', '\n  ')
    context = Context({
        'catalog_str': indent(json.dumps(
            catalog, sort_keys=True, indent=2)) if catalog else None,
        'formats_str': indent(json.dumps(
            get_formats(), sort_keys=True, indent=2)),
        'plural': plural,
    })

    return http.HttpResponse(template.render(context), 'text/javascript') 
Example 16
Project: GTDWeb   Author: lanbing510   File: csrf.py    License: GNU General Public License v2.0 5 votes vote down vote up
def csrf_failure(request, reason=""):
    """
    Default view used when request fails CSRF protection
    """
    from django.middleware.csrf import REASON_NO_REFERER, REASON_NO_CSRF_COOKIE
    t = Engine().from_string(CSRF_FAILURE_TEMPLATE)
    c = Context({
        'title': _("Forbidden"),
        'main': _("CSRF verification failed. Request aborted."),
        'reason': reason,
        'no_referer': reason == REASON_NO_REFERER,
        'no_referer1': _(
            "You are seeing this message because this HTTPS site requires a "
            "'Referer header' to be sent by your Web browser, but none was "
            "sent. This header is required for security reasons, to ensure "
            "that your browser is not being hijacked by third parties."),
        'no_referer2': _(
            "If you have configured your browser to disable 'Referer' headers, "
            "please re-enable them, at least for this site, or for HTTPS "
            "connections, or for 'same-origin' requests."),
        'no_cookie': reason == REASON_NO_CSRF_COOKIE,
        'no_cookie1': _(
            "You are seeing this message because this site requires a CSRF "
            "cookie when submitting forms. This cookie is required for "
            "security reasons, to ensure that your browser is not being "
            "hijacked by third parties."),
        'no_cookie2': _(
            "If you have configured your browser to disable cookies, please "
            "re-enable them, at least for this site, or for 'same-origin' "
            "requests."),
        'DEBUG': settings.DEBUG,
        'docs_version': get_docs_version(),
        'more': _("More information is available with DEBUG=True."),
    })
    return HttpResponseForbidden(t.render(c), content_type='text/html') 
Example 17
Project: django-csp-reports   Author: adamalton   File: summary.py    License: MIT License 5 votes vote down vote up
def render(self):
        """Render the summary."""
        engine = Engine()
        return engine.from_string(SUMMARY_TEMPLATE).render(Context(self.__dict__)) 
Example 18
Project: bioforum   Author: reBiocoder   File: i18n.py    License: MIT License 5 votes vote down vote up
def render_javascript_catalog(catalog=None, plural=None):
    template = Engine().from_string(js_catalog_template)

    def indent(s):
        return s.replace('\n', '\n  ')

    context = Context({
        'catalog_str': indent(json.dumps(
            catalog, sort_keys=True, indent=2)) if catalog else None,
        'formats_str': indent(json.dumps(
            get_formats(), sort_keys=True, indent=2)),
        'plural': plural,
    })

    return HttpResponse(template.render(context), 'text/javascript') 
Example 19
Project: bioforum   Author: reBiocoder   File: i18n.py    License: MIT License 5 votes vote down vote up
def render_to_response(self, context, **response_kwargs):
        def indent(s):
            return s.replace('\n', '\n  ')

        template = Engine().from_string(js_catalog_template)
        context['catalog_str'] = indent(
            json.dumps(context['catalog'], sort_keys=True, indent=2)
        ) if context['catalog'] else None
        context['formats_str'] = indent(json.dumps(context['formats'], sort_keys=True, indent=2))

        return HttpResponse(template.render(Context(context)), 'text/javascript') 
Example 20
Project: bioforum   Author: reBiocoder   File: defaults.py    License: MIT License 5 votes vote down vote up
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME):
    """
    Default 404 handler.

    Templates: :template:`404.html`
    Context:
        request_path
            The path of the requested URL (e.g., '/app/pages/bad_page/')
        exception
            The message from the exception which triggered the 404 (if one was
            supplied), or the exception class name
    """
    exception_repr = exception.__class__.__name__
    # Try to get an "interesting" exception message, if any (and not the ugly
    # Resolver404 dictionary)
    try:
        message = exception.args[0]
    except (AttributeError, IndexError):
        pass
    else:
        if isinstance(message, str):
            exception_repr = message
    context = {
        'request_path': request.path,
        'exception': exception_repr,
    }
    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None             # Django will use DEFAULT_CONTENT_TYPE
    except TemplateDoesNotExist:
        if template_name != ERROR_404_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        template = Engine().from_string(
            '<h1>Not Found</h1>'
            '<p>The requested URL {{ request_path }} was not found on this server.</p>')
        body = template.render(Context(context))
        content_type = 'text/html'
    return HttpResponseNotFound(body, content_type=content_type) 
Example 21
Project: DeerU   Author: gojuukaze   File: install.py    License: GNU General Public License v3.0 5 votes vote down vote up
def install_project(self):
        self.info('开始安装DeerU')

        self.info('下载DeerU ...')

        s = ''
        if os.path.exists(self.name):
            # self.info('已存在相同目录 "%s" ,请选择: d(删除已存在目录); s(跳过下载) ' % self.name)
            s = input('已存在相同目录 "%s" ,请选择: d(删除已存在目录); s(跳过下载): ' % self.name)
            if s == 'd':
                shutil.rmtree(self.name)
            elif s == 's':
                pass
            else:
                raise CommandError('输入错误')

        if s != 's':
            result = subprocess.run('git clone -b %s %s %s' % (self.branch, self.DEERU_GIT_URL, self.name), shell=True)
            if result.returncode != 0:
                raise CommandError('\n下载DeerU失败')

        self.info('安装依赖...')
        result = subprocess.run('pip install -r requirements.txt', cwd=self.name, shell=True)
        if result.returncode != 0:
            raise CommandError('\n安装依赖失败')

        self.info('复制必要文件...')

        context = Context({'SECRET_KEY': get_random_secret_key()}, autoescape=False)

        for template_name, new_file in self.get_project_templates():
            template = Engine().from_string(self.get_template_str(template_name))
            content = template.render(context)
            new_file.write_text(content)

        self.success('\n安装完成 !!') 
Example 22
Project: xblock-utils   Author: edx   File: resources.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def render_django_template(self, template_path, context=None, i18n_service=None):
        """
        Evaluate a django template by resource path, applying the provided context.
        """
        context = context or {}
        context['_i18n_service'] = i18n_service
        libraries = {
            'i18n': 'xblockutils.templatetags.i18n',
        }

        # For django 1.8, we have to load the libraries manually, and restore them once the template is rendered.
        _libraries = None
        if django.VERSION[0] == 1 and django.VERSION[1] == 8:
            _libraries = TemplateBase.libraries.copy()
            for library_name in libraries:
                library = TemplateBase.import_library(libraries[library_name])  # pylint: disable=no-member
                if library:
                    TemplateBase.libraries[library_name] = library
            engine = Engine()
        else:
            # Django>1.8 Engine can load the extra templatetag libraries itself
            # but we have to override the default installed libraries.
            from django.template.backends.django import get_installed_libraries
            installed_libraries = get_installed_libraries()
            installed_libraries.update(libraries)
            engine = Engine(libraries=installed_libraries)

        template_str = self.load_unicode(template_path)
        template = Template(template_str, engine=engine)
        rendered = template.render(Context(context))

        # Restore the original TemplateBase.libraries
        if _libraries is not None:
            TemplateBase.libraries = _libraries

        return rendered 
Example 23
Project: django-tenants   Author: django-tenants   File: test_filesystem.py    License: MIT License 5 votes vote down vote up
def setUpClass(cls):
        cls.engine = Engine(
            loaders=["django_tenants.template.loaders.filesystem.Loader"]
        )

        super().setUpClass() 
Example 24
Project: django-tenants   Author: django-tenants   File: test_filesystem.py    License: MIT License 5 votes vote down vote up
def setUpClass(cls):
        test_app_root = settings.TENANT_APPS_DIR
        settings.MULTITENANT_TEMPLATE_DIRS = [
            os.path.join(test_app_root, "tenants/%s/templates")
        ]
        cls.engine = Engine(
            loaders=["django_tenants.template.loaders.filesystem.Loader"]
        )

        super().setUpClass() 
Example 25
Project: xblock-video   Author: appsembler   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def render_template(template_name, **context):
    """
    Render static resource using provided context.

    Returns: django.utils.safestring.SafeText
    """
    template_dirs = [os.path.join(os.path.dirname(__file__), 'static/html')]
    engine = Engine(dirs=template_dirs, debug=True)
    html = engine.get_template(template_name)

    return html_parser.unescape(
        html.render(Context(context))
    ) 
Example 26
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: i18n.py    License: MIT License 5 votes vote down vote up
def render_javascript_catalog(catalog=None, plural=None):
    template = Engine().from_string(js_catalog_template)

    def indent(s):
        return s.replace('\n', '\n  ')

    context = Context({
        'catalog_str': indent(json.dumps(
            catalog, sort_keys=True, indent=2)) if catalog else None,
        'formats_str': indent(json.dumps(
            get_formats(), sort_keys=True, indent=2)),
        'plural': plural,
    })

    return HttpResponse(template.render(context), 'text/javascript') 
Example 27
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: i18n.py    License: MIT License 5 votes vote down vote up
def render_to_response(self, context, **response_kwargs):
        def indent(s):
            return s.replace('\n', '\n  ')

        template = Engine().from_string(js_catalog_template)
        context['catalog_str'] = indent(
            json.dumps(context['catalog'], sort_keys=True, indent=2)
        ) if context['catalog'] else None
        context['formats_str'] = indent(json.dumps(context['formats'], sort_keys=True, indent=2))

        return HttpResponse(template.render(Context(context)), 'text/javascript; charset="utf-8"') 
Example 28
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: defaults.py    License: MIT License 5 votes vote down vote up
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME):
    """
    Default 404 handler.

    Templates: :template:`404.html`
    Context:
        request_path
            The path of the requested URL (e.g., '/app/pages/bad_page/'). It's
            quoted to prevent a content injection attack.
        exception
            The message from the exception which triggered the 404 (if one was
            supplied), or the exception class name
    """
    exception_repr = exception.__class__.__name__
    # Try to get an "interesting" exception message, if any (and not the ugly
    # Resolver404 dictionary)
    try:
        message = exception.args[0]
    except (AttributeError, IndexError):
        pass
    else:
        if isinstance(message, str):
            exception_repr = message
    context = {
        'request_path': quote(request.path),
        'exception': exception_repr,
    }
    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None             # Django will use DEFAULT_CONTENT_TYPE
    except TemplateDoesNotExist:
        if template_name != ERROR_404_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        template = Engine().from_string(
            '<h1>Not Found</h1>'
            '<p>The requested resource was not found on this server.</p>')
        body = template.render(Context(context))
        content_type = 'text/html'
    return HttpResponseNotFound(body, content_type=content_type) 
Example 29
Project: python   Author: Yeah-Kun   File: i18n.py    License: Apache License 2.0 5 votes vote down vote up
def render_javascript_catalog(catalog=None, plural=None):
    template = Engine().from_string(js_catalog_template)

    def indent(s):
        return s.replace('\n', '\n  ')

    context = Context({
        'catalog_str': indent(json.dumps(
            catalog, sort_keys=True, indent=2)) if catalog else None,
        'formats_str': indent(json.dumps(
            get_formats(), sort_keys=True, indent=2)),
        'plural': plural,
    })

    return http.HttpResponse(template.render(context), 'text/javascript') 
Example 30
Project: python   Author: Yeah-Kun   File: i18n.py    License: Apache License 2.0 5 votes vote down vote up
def render_to_response(self, context, **response_kwargs):
        def indent(s):
            return s.replace('\n', '\n  ')

        template = Engine().from_string(js_catalog_template)
        context['catalog_str'] = indent(
            json.dumps(context['catalog'], sort_keys=True, indent=2)
        ) if context['catalog'] else None
        context['formats_str'] = indent(json.dumps(context['formats'], sort_keys=True, indent=2))

        return http.HttpResponse(template.render(Context(context)), 'text/javascript')