Python django.template() Examples

The following are 30 code examples of django.template(). 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 , or try the search function .
Example #1
Source File: test_resources.py    From personfinder with Apache License 2.0 6 votes vote down vote up
def test_get(self):
        # Verify that Resource.get fetches a Resource from the datastore.
        assert Resource.get('xyz', '1') is None
        self.put_resource('1', 'xyz', 10, 'pqr')
        assert Resource.get('xyz', '1').content == 'pqr'
        self.delete_resource('1', 'xyz')
        assert Resource.get('xyz', '1') is None

        # Verify that Resource.get fetches a Resource from an existing file.
        content = Resource.get('message.html.template', '1').content
        assert content != 'pqr'

        # Verify that the file can be overriden by a datastore entity.
        self.put_resource('1', 'message.html.template', 10, 'pqr')
        assert Resource.get('message.html.template', '1').content == 'pqr'
        self.delete_resource('1', 'message.html.template')
        assert Resource.get('message.html.template', '1').content == content 
Example #2
Source File: templates.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example #3
Source File: handlers.py    From gae-secure-scaffold-python with Apache License 2.0 6 votes vote down vote up
def render_to_string(self, template, template_values=None):
    """Renders template_name with template_values and returns as a string."""
    if not template_values:
      template_values = {}

    template_values['_xsrf'] = self._xsrf_token
    template_values['_csp_nonce'] = self.csp_nonce
    template_strategy = self.app.config.get('template', constants.CLOSURE)

    if template_strategy == constants.DJANGO:
      t = django.template.loader.get_template(template)
      template_values = django.template.Context(template_values)
      return t.render(template_values)
    elif template_strategy == constants.JINJA2:
      return self.jinja2.render_template(template, **template_values)
    else:
      ijdata = { 'csp_nonce': self.csp_nonce }
      return template(template_values, ijdata) 
Example #4
Source File: util.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def Home(request):
    """Our Home page.
    This also doubles as a general API request handler with a few specific
    bits for the home page template."""

    # The recent tests table.
    recent_tests = memcache.get(key=RECENT_TESTS_MEMCACHE_KEY)
    if not recent_tests:
        ScheduleRecentTestsUpdate()

    show_evolution = False

    params = {
        'page_title': 'Home',
        'message': request.GET.get('message'),
        'recent_tests': recent_tests,
        'show_evolution': show_evolution,
    }
    return GetResults(request, template='home.html', params=params,
                                        do_sparse_filter=True) 
Example #5
Source File: util.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def GetStatsDataTemplatized(params, template='table'):
    """Returns the stats table run through a template.

    Args:
        params: Example:
                        params = {
                            'v': one of the keys in user_agent.BROWSER_NAV,
                            'current_user_agent': a user agent entity,
                            'user_agents': list_of user agents,
                            'tests': list of test names,
                            'stats': dict - stats[test_name][user_agent],
                            'total_runs': total_runs[test_name],
                            'request_path': request.path,
                            'params': result_parent.params, #optional
                        }

    """
    params['browser_nav'] = result_stats.BROWSER_NAV
    params['is_admin'] = users.is_current_user_admin()
    if not re.search('\?', params['request_path']):
        params['request_path'] = params['request_path'] + '?'
    t = loader.get_template('stats_%s.html' % template)
    template_rendered = t.render(Context(params))
    return template_rendered 
Example #6
Source File: handlers.py    From gae-secure-scaffold-python with Apache License 2.0 6 votes vote down vote up
def __init__(self, request, response):
    self.initialize(request, response)
    api_fixer.ReplaceDefaultArgument(response.set_cookie.im_func, 'secure',
                                     not constants.IS_DEV_APPSERVER)
    api_fixer.ReplaceDefaultArgument(response.set_cookie.im_func, 'httponly',
                                     True)
    if self.current_user:
      self._xsrf_token = xsrf.GenerateToken(_GetXsrfKey(),
                                            self.current_user.email())
      if self.app.config.get('using_angular', constants.DEFAULT_ANGULAR):
        # AngularJS requires a JS readable XSRF-TOKEN cookie and will pass this
        # back in AJAX requests.
        self.response.set_cookie('XSRF-TOKEN', self._xsrf_token, httponly=False)
    else:
      self._xsrf_token = None

    self.csp_nonce = _GetCspNonce()

    self._RawWrite = self.response.out.write
    self.response.out.write = self._ReplacementWrite

  # All content should be rendered through a template system to reduce the
  # risk/likelihood of XSS issues.  Access to the original function
  # self.response.out.write is available via self._RawWrite for exceptional
  # circumstances. 
Example #7
Source File: fluent_comments_tags.py    From DCRM with GNU Affero General Public License v3.0 6 votes vote down vote up
def parse(cls, parser, token):
        """
        Custom parsing for the ``{% ajax_comment_tags for ... %}`` tag.
        """
        # Process the template line.
        tag_name, args, kwargs = parse_token_kwargs(
            parser, token,
            allowed_kwargs=cls.allowed_kwargs,
            compile_args=False,  # Only overrule here, keep at render() phase.
            compile_kwargs=cls.compile_kwargs
        )

        # remove "for" keyword, so all other args can be resolved in render().
        if args[0] == 'for':
            args.pop(0)

        # And apply the compilation afterwards
        for i in range(len(args)):
            args[i] = parser.compile_filter(args[i])

        cls.validate_args(tag_name, *args, **kwargs)
        return cls(tag_name, *args, **kwargs) 
Example #8
Source File: __init__.py    From django-compat with MIT License 6 votes vote down vote up
def get_template_loaders():
    """
    Compatibility method to fetch the template loaders.
    Source: https://github.com/django-debug-toolbar/django-debug-toolbar/blob/ece1c2775af108a92a0ef59636266b49e286e916/debug_toolbar/compat.py
    """
    try:
        from django.template.engine import Engine
    except ImportError:  # Django < 1.8
        Engine = None

    if Engine:
        try:
            engine = Engine.get_default()
        except ImproperlyConfigured:
            loaders = []
        else:
            loaders = engine.template_loaders
    else:  # Django < 1.8
        from django.template.loader import find_template_loader
        loaders = [
            find_template_loader(loader_name)
            for loader_name in settings.TEMPLATE_LOADERS]
    return loaders 
Example #9
Source File: test_compat.py    From django-compat with MIT License 6 votes vote down vote up
def test_add_to_builtins(self):
            from compat import add_to_builtins

            # Explicit import of tags
            template = Template(
                '{% load test_app_tags %}'
                '{% my_tag %}'
            )
            self.assertIn('Return value of my_tag', template.render(Context({})))

            # No import
            with self.assertRaises(TemplateSyntaxError):
                template = Template(
                    '{% my_tag %}'
                )
                template.render(Context({}))

            # No import but add_to_builtins call
            add_to_builtins('compat.tests.test_app.templatetags.test_app_tags')
            template = Template(
                '{% my_tag %}'
            )
            self.assertIn('Return value of my_tag', template.render(Context({}))) 
Example #10
Source File: resources.py    From xblock-utils with GNU Affero General Public License v3.0 6 votes vote down vote up
def load_scenarios_from_path(self, relative_scenario_dir, include_identifier=False):
        """
        Returns an array of (title, xmlcontent) from files contained in a specified directory,
        formatted as expected for the return value of the workbench_scenarios() method.

        If `include_identifier` is True, returns an array of (identifier, title, xmlcontent).
        """
        base_dir = os.path.dirname(os.path.realpath(sys.modules[self.module_name].__file__))
        scenario_dir = os.path.join(base_dir, relative_scenario_dir)

        scenarios = []
        if os.path.isdir(scenario_dir):
            for template in sorted(os.listdir(scenario_dir)):
                if not template.endswith('.xml'):
                    continue
                identifier = template[:-4]
                title = identifier.replace('_', ' ').title()
                template_path = os.path.join(relative_scenario_dir, template)
                scenario = str(self.render_django_template(template_path, {"url_name": identifier}))
                if not include_identifier:
                    scenarios.append((title, scenario))
                else:
                    scenarios.append((identifier, title, scenario))

        return scenarios 
Example #11
Source File: templates.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example #12
Source File: plugin.py    From django_coverage_plugin with Apache License 2.0 6 votes vote down vote up
def read_template_source(filename):
    """Read the source of a Django template, returning the Unicode text."""
    # Import this late to be sure we don't trigger settings machinery too
    # early.
    from django.conf import settings

    if not settings.configured:
        settings.configure()

    with open(filename, "rb") as f:
        # The FILE_CHARSET setting will be removed in 3.1:
        # https://docs.djangoproject.com/en/3.0/ref/settings/#file-charset
        if django.VERSION >= (3, 1):
            charset = 'utf-8'
        else:
            charset = settings.FILE_CHARSET
        text = f.read().decode(charset)

    return text 
Example #13
Source File: plugin.py    From django_coverage_plugin with Apache License 2.0 6 votes vote down vote up
def get_line_map(self, filename):
        """The line map for `filename`.

        A line map is a list of character offsets, indicating where each line
        in the text begins.  For example, a line map like this::

            [13, 19, 30]

        means that line 2 starts at character 13, line 3 starts at 19, etc.
        Line 1 always starts at character 0.

        """
        if filename not in self.source_map:
            template_source = read_template_source(filename)
            if 0:   # change to see the template text
                for i in range(0, len(template_source), 10):
                    print("%3d: %r" % (i, template_source[i:i+10]))
            self.source_map[filename] = make_line_map(template_source)
        return self.source_map[filename] 
Example #14
Source File: organice_setup.py    From django-organice with Apache License 2.0 5 votes vote down vote up
def _configure_newsletter():
    global settings

    _print_verbose(2, adding_settings_for('Emencia Newsletter'))
    settings.append_lines('common',
                          "NEWSLETTER_DEFAULT_HEADER_SENDER = 'Your Organization <newsletter@your.domain>'",
                          'NEWSLETTER_USE_TINYMCE = True',
                          'NEWSLETTER_TEMPLATES = [',
                          "    {",
                          "        'title': 'Sample template for newsletter',",
                          "        'src': '/media/newsletter/templates/sample-template.html',",
                          "        'description': 'Newsletter template tabular sample',",
                          "    },",
                          ']',
                          'TINYMCE_DEFAULT_CONFIG = {',
                          "    'height': 450,",
                          "    'width': 800,",
                          "    'convert_urls': False,",
                          "    'plugins': 'table,paste,searchreplace,template,advlist,autolink,autosave',",
                          "    'template_templates': NEWSLETTER_TEMPLATES,",
                          "    'theme': 'advanced',",
                          "    'theme_advanced_toolbar_location': 'top',",
                          "    'theme_advanced_buttons1':",
                          "        'template,|,formatselect,'",
                          "        '|,bold,italic,underline,strikethrough,|,undo,redo,'",
                          "        '|,justifyleft,justifycenter,justifyright,justifyfull,'",
                          "        '|,bullist,numlist,dt,dd,|,outdent,indent,|,blockquote',",
                          "    'theme_advanced_buttons2':",
                          "        'tablecontrols,|,forecolor,backcolor,'",
                          "        '|,hr,image,anchor,link,unlink,|,visualaid,code',",
                          "    'theme_advanced_resizing': True,",
                          '}') 
Example #15
Source File: organice_setup.py    From django-organice with Apache License 2.0 5 votes vote down vote up
def _configure_templates():
    global args
    global settings

    _print_verbose(2, adding_settings_for('Django templates'))
    settings.delete_from_list('common',
                              ["TEMPLATES = [", "{"],
                              "'APP_DIRS': True")
    settings.append_to_list('common',
                            ["TEMPLATES = [", "{", "'DIRS': ["],
                            "join(BASE_DIR, '%s.templates')" % args.projectname,
                            "join(BASE_DIR, '%s.templates', 'zinnia')" % args.projectname)
    settings.append_to_list('common',
                            ["TEMPLATES = [", "{", "'OPTIONS': {", "'context_processors': ["],
                            "'django.template.context_processors.i18n'",
                            "'django.template.context_processors.media'",
                            "'django.template.context_processors.static'",
                            "'sekizai.context_processors.sekizai'",
                            "'cms.context_processors.cms_settings'",
                            "'organice.context_processors.expose'")
    settings.append_to_list('common',
                            ["TEMPLATES = [", "{", "'OPTIONS': {"],
                            "'loaders': []")
    settings.append_to_list('common',
                            ["TEMPLATES = [", "{", "'OPTIONS': {", "'loaders': ["],
                            "'apptemplates.Loader'",
                            "'django.template.loaders.filesystem.Loader'",
                            "'django.template.loaders.app_directories.Loader'")
    settings.append_to_list('common',
                            ["TEMPLATES = [", "{", "'OPTIONS': {"],
                            "# 'string_if_invalid': '|INVALID) %s (INVALID|'",
                            "# see https://docs.djangoproject.com/en/stable/ref/settings/#template-string-if-invalid ") 
Example #16
Source File: utils.py    From django-cas-server with GNU General Public License v3.0 5 votes vote down vote up
def do_GET(self):
        """Called on a GET request on the BaseHTTPServer"""
        url = urlparse(self.path)
        self.params = dict(parse_qsl(url.query))
        if url.path == "/validate":
            self.send_headers(200, "text/plain; charset=utf-8")
            if self.test_params():
                self.wfile.write(b"yes\n" + self.server.username + b"\n")
                self.server.ticket = None
            else:
                self.wfile.write(b"no\n")
        elif url.path in {
            '/serviceValidate', '/serviceValidate',
            '/p3/serviceValidate', '/p3/proxyValidate'
        }:
            self.send_headers(200, "text/xml; charset=utf-8")
            if self.test_params():
                template = loader.get_template('cas_server/serviceValidate.xml')
                context = Context({
                    'username': self.server.username.decode('utf-8'),
                    'attributes': self.server.attributes,
                    'auth_date': timezone.now().replace(microsecond=0).isoformat(),
                    'is_new_login': 'true',
                })
                self.wfile.write(return_bytes(template.render(context), "utf8"))
            else:
                template = loader.get_template('cas_server/serviceValidateError.xml')
                context = Context({
                    'code': 'BAD_SERVICE_TICKET',
                    'msg': 'Valids are (%r, %r)' % (self.server.service, self.server.ticket)
                })
                self.wfile.write(return_bytes(template.render(context), "utf8"))
        else:
            self.return_404() 
Example #17
Source File: organice_setup.py    From django-organice with Apache License 2.0 5 votes vote down vote up
def _configure_database():
    global args
    global settings

    db_template = django.template.Template("""{
    'default': {
        'ENGINE': 'django.db.backends.{{ engine }}',  # 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': {{ database|safe }},  # path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': '{{ username|safe }}',
        'PASSWORD': '{{ password|safe }}',
        'HOST': '',  # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '',  # Set to empty string for default.
    }
}""")
    db_context = django.template.Context({
        'engine': 'sqlite3',
        'database': "join(BASE_DIR, '%s.sqlite')" % args.projectname,
        'username': '',
        'password': '',
    })

    _print_verbose(2, 'Configuring database for all profiles ...')
    settings.set_value('develop', 'DATABASES', db_template.render(db_context))

    db_context['engine'] = args.engine if args.engine else ''
    db_context['database'] = "'%s'" % (args.database if args.database else '')
    db_context['username'] = args.username if args.username else ''
    db_context['password'] = args.password if args.password else ''

    for prof in ('staging', 'production'):
        settings.set_value(prof, 'DATABASES', db_template.render(db_context)) 
Example #18
Source File: render_benchmark.py    From spitfire with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_cheetah_tests():
    if not Cheetah:
        return []

    tmpl_src = """
        <table>
            #for $row in $table
                <tr>
                    #for $column in $row.values()
                        <td>$column</td>
                    #end for
                </tr>
            #end for
        </table>
    """

    tmpl_search_list = [{'table': TABLE_DATA}]

    tmpl = Cheetah.Template.Template(tmpl_src, searchList=tmpl_search_list)

    def test_cheetah():
        """Cheetah template"""
        tmpl.respond()

    return [
        test_cheetah,
    ] 
Example #19
Source File: wagtailmodeladmin_tags.py    From wagtailmodeladmin with MIT License 5 votes vote down vote up
def admin_list_filter(view, spec):
    template_name = spec.template
    if template_name == 'admin/filter.html':
        template_name = 'wagtailmodeladmin/includes/filter.html'
    tpl = get_template(template_name)
    return tpl.render({
        'title': spec.title,
        'choices': list(spec.choices(view)),
        'spec': spec,
    }) 
Example #20
Source File: plugin_test.py    From django_coverage_plugin with Apache License 2.0 5 votes vote down vote up
def get_xml_report(self, name=None):
        """Get the xml report for a template.

        Returns:
            float: the total percentage covered.

        """
        path = self._path(name)
        xml_coverage = self.cov.xml_report(os.path.abspath(path))
        return xml_coverage 
Example #21
Source File: plugin_test.py    From django_coverage_plugin with Apache License 2.0 5 votes vote down vote up
def get_html_report(self, name=None):
        """Get the html report for a template.

        Returns:
            float: the total percentage covered.

        """
        path = self._path(name)
        html_coverage = self.cov.html_report(os.path.abspath(path))
        return html_coverage 
Example #22
Source File: plugin_test.py    From django_coverage_plugin with Apache License 2.0 5 votes vote down vote up
def get_analysis(self, name=None):
        """Get the coverage analysis for a template.

        Returns:
            list, list: the line numbers of executable lines, and the line
                numbers of missed lines.

        """
        path = self._path(name)
        analysis = self.cov.analysis2(os.path.abspath(path))
        _, executable, _, missing, _ = analysis
        return executable, missing 
Example #23
Source File: plugin_test.py    From django_coverage_plugin with Apache License 2.0 5 votes vote down vote up
def get_line_data(self, name=None):
        """Get the executed-line data for a template.

        Returns:
            list: the line numbers of lines executed in the template.

        """
        path = self._path(name)
        line_data = self.cov.data.line_data()[os.path.realpath(path)]
        return line_data 
Example #24
Source File: plugin_test.py    From django_coverage_plugin with Apache License 2.0 5 votes vote down vote up
def test_settings():
    """Create a dict full of default Django settings for the tests."""
    the_settings = {
        'CACHES': {
            'default': {
                'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
            },
        },
        'DATABASES': {
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:',
            }
        },
        'ROOT_URLCONF': 'tests',
    }

    the_settings.update({
        'TEMPLATES': [
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'DIRS': ['templates'],      # where the tests put things.
                'OPTIONS': {
                    'debug': True,
                },
            },
        ],
    })

    if django.VERSION < (1, 10):
        # for {% ssi %}
        the_settings['TEMPLATES'][0]['OPTIONS']['allowed_include_roots'] = ['/']

    return the_settings 
Example #25
Source File: handlers.py    From gae-secure-scaffold-python with Apache License 2.0 5 votes vote down vote up
def render(self, template, template_values=None):
    """Renders template with template_values and writes to the response."""
    template_strategy = self.app.config.get('template', constants.CLOSURE)
    self._RawWrite(self.render_to_string(template, template_values)) 
Example #26
Source File: plugin.py    From django_coverage_plugin with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.debug_checked = False

        self.django_template_dir = os.path.realpath(
            os.path.dirname(django.template.__file__)
        )

        self.source_map = {}

    # --- CoveragePlugin methods 
Example #27
Source File: test_resources.py    From personfinder with Apache License 2.0 5 votes vote down vote up
def tearDown(self):
        utils.set_utcnow_for_test(None)
        resources.clear_caches()

        Resource.get_by_key_name = self.resource_get_by_key_name_original
        webapp.template.Template.__init__ = self.template_init_original
        webapp.template.Template.render = self.template_render_original

        db.delete(self.temp_entity_keys) 
Example #28
Source File: templates.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def is_url(self, template):
        """
        Returns True if the name looks like a URL
        """
        if ':' not in template:
            return False
        scheme = template.split(':', 1)[0].lower()
        return scheme in self.url_schemes 
Example #29
Source File: plugin.py    From django_coverage_plugin with Apache License 2.0 5 votes vote down vote up
def check_debug():
    """Check that Django's template debugging is enabled.

    Django's built-in "template debugging" records information the plugin needs
    to do its work.  Check that the setting is correct, and raise an exception
    if it is not.

    Returns True if the debug check was performed, False otherwise
    """
    from django.conf import settings

    if not settings.configured:
        return False

    # I _think_ this check is all that's needed and the 3 "hasattr" checks
    # below can be removed, but it's not clear how to verify that
    from django.apps import apps
    if not apps.ready:
        return False

    # django.template.backends.django gets loaded lazily, so return false
    # until they've been loaded
    if not hasattr(django.template, "backends"):
        return False
    if not hasattr(django.template.backends, "django"):
        return False
    if not hasattr(django.template.backends.django, "DjangoTemplates"):
        raise DjangoTemplatePluginException("Can't use non-Django templates.")

    for engine in django.template.engines.all():
        if not isinstance(engine, django.template.backends.django.DjangoTemplates):
            raise DjangoTemplatePluginException(
                "Can't use non-Django templates."
            )
        if not engine.engine.debug:
            raise DjangoTemplatePluginException(
                "Template debugging must be enabled in settings."
            )

    return True 
Example #30
Source File: render_benchmark.py    From spitfire with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_django_tests():
    if not django:
        return []

    django.conf.settings.configure()
    django.setup()

    tmpl_src = """
        <table>
            {% for row in table %}
                <tr>
                    {% for column in row.values %}
                        <td>{{ column }}</td>
                    {% endfor %}
                </tr>
            {% endfor %}
        </table>
    """
    tmpl_autoescaped_src = ('{% autoescape on %}' +
                            tmpl_src +
                            '{% endautoescape %}')

    tmpl = django.template.Template(tmpl_src)
    tmpl_autoescaped = django.template.Template(tmpl_autoescaped_src)

    tmpl_context = django.template.Context({'table': TABLE_DATA})

    def test_django():
        """Django template"""
        tmpl.render(tmpl_context)

    def test_django_autoescaped():
        """Django template autoescaped"""
        tmpl_autoescaped.render(tmpl_context)

    return [
        test_django,
        test_django_autoescaped,
    ]