Python django.template() Examples

The following are code examples for showing how to use django.template(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: openhatch   Author: campbe13   File: views.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def suggest_question_do(request):
    project = mysite.search.models.Project.objects.get(
        pk=request.POST['project__pk'])
    user = request.user
    body = request.POST['suggested_question']
    body += "\nproject name: " + project.name
    body += "\nproject display name: " + project.display_name
    body += "\nproject pk: " + str(project.pk)
    body += "\nuser name: " + user.username
    body += "\nuser pk: " + str(user.pk)
    question_suggestion_response = ""
    # TODO: Asheesh would really rather this be enqueued as a background job
    try:
        send_mail('Project Page Question Suggestion: ', body,
                  '[email protected]', ['[email protected]'], fail_silently=False)
        question_suggestion_response = "success"
    except socket.error:
        # NOTE: this will probably only happen on a local server (not on the
        # live site)
        question_suggestion_response = "failure"
    template = "project/project.html"
    return HttpResponseRedirect(reverse(mysite.project.views.project, kwargs={'project__name': project.name}) + '?question_suggestion_response=' + question_suggestion_response) 
Example 2
Project: django-jsx   Author: caktus   File: compilejsx.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def list_template_files():
    """
    Return list of template files everywhere Django looks for them.
    """
    engines = django.template.engines

    template_dirs = []
    # 'engines' is not a dictionary, it just behaves like one in some ways
    for engine_name in engines:
        engine = engines[engine_name]
        if isinstance(engine, DjangoTemplates):
            # We only handle Django templates
            template_dirs.extend(engine.template_dirs)

    template_list = []
    for each in template_dirs:
        for dir, dirnames, filenames in os.walk(each):
            for filename in filenames:
                template_list.append(os.path.join(dir, filename))
    return template_list 
Example 3
Project: GTDWeb   Author: lanbing510   File: templates.py    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 4
Project: DCRM   Author: 82Flex   File: fluent_comments_tags.py    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 5
Project: django-dox   Author: mhulse   File: views.py    Apache License 2.0 6 votes vote down vote up
def render_page(request, f):
    
    if f.login_required and not request.user.is_authenticated():
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.path)
    
    if f.template_name:
        template = DEFAULT_TEMPLATE.replace('default.html', f.template_name) # Saves user from having to type "dox/" path.
        t = loader.select_template((template, DEFAULT_TEMPLATE))
    else:
        t = loader.get_template(DEFAULT_TEMPLATE)
    
    f.title = mark_safe(f.title)
    f.content = mark_safe(f.content)
    
    c = RequestContext(request, {
        'page': f,
    })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, Page, f.id)
    return response 
Example 6
Project: openode   Author: JvGinkel   File: django_patches.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def add_csrf_protection():
    """adds csrf_token template tag to django
    Must be used if version of django is < 1.2

    Also adds csrf function to the context processor
    and the csrf_protect decorator for the views
    """
    import django.template.defaulttags
    def csrf_token(parser, token):
        return CsrfTokenNode()
    django.template.defaulttags.CsrfTokenNode = CsrfTokenNode
    django.template.defaulttags.register.tag(csrf_token)

    #add csrf context processor
    import django.core.context_processors
    django.core.context_processors.csrf = csrf

    #add csrf_protect decorator
    import django.views.decorators
    django.views.decorators.csrf = imp.new_module('csrf') 
    django.views.decorators.csrf.csrf_protect = csrf_protect 
Example 7
Project: django-compiling-loader   Author: mhallin   File: run_benchmark.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_timings(template_name, iterations, ctx_dict, profile=False):
    from django.template import Context
    from django.template.loader import get_template

    template = get_template(template_name)
    print('Found template {} for name {}'.format(template, template_name))
    # print('rendered: {}'.format(template.render(Context(ctx_dict))))

    if profile:
        profiler = cProfile.Profile()
        profiler.enable()

    start_time = TIMER()
    for i in range(iterations):
        template.render(Context(ctx_dict))
    end_time = TIMER()

    if profile:
        profiler.disable()

        pstats.Stats(profiler).dump_stats('profile.pstats')

    return (end_time - start_time) / iterations 
Example 8
Project: django-compiling-loader   Author: mhallin   File: run_benchmark.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_bench():
    main_count = 10000
    main_ctx = {}

    loop_count = 20
    loop_ctx = {'data': generate_test_data(2000)}

    switch_loader_settings(NATIVE_LOADER_SETTINGS)
    native_main = run_timings('benchmark/main.html', main_count, main_ctx)
    native_loop = run_timings('benchmark/loop.html', loop_count, loop_ctx)

    switch_loader_settings(COMPILED_LOADER_SETTINGS)
    compiled_main = run_timings('benchmark/main.html', main_count, main_ctx)
    compiled_loop = run_timings('benchmark/loop.html', loop_count, loop_ctx)#, profile=True)

    print('Native main template:   {:.5}'.format(1000 * native_main))
    print('Compiled main template: {:.5}'.format(1000 * compiled_main))
    print('Fractional time: {:.3}'.format(compiled_main / native_main))

    print('Native loop template:   {:.5}'.format(1000 * native_loop))
    print('Compiled loop template: {:.5}'.format(1000 * compiled_loop))
    print('Fractional time: {:.3}'.format(compiled_loop / native_loop)) 
Example 9
Project: taiga-back-   Author: andyzsf   File: renderers.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        Renders data to HTML, using Django's standard template rendering.

        The template name is determined by (in order of preference):

        1. An explicit .template_name set on the response.
        2. An explicit .template_name set on this class.
        3. The return result of calling view.get_template_names().
        """
        renderer_context = renderer_context or {}
        view = renderer_context["view"]
        request = renderer_context["request"]
        response = renderer_context["response"]

        if response.exception:
            template = self.get_exception_template(response)
        else:
            template_names = self.get_template_names(response, view)
            template = self.resolve_template(template_names)

        context = self.resolve_context(data, request, response)
        return template.render(context) 
Example 10
Project: luscan-devel   Author: blackye   File: templates.py    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 11
Project: django-async-include   Author: diegojromerolopez   File: test_async_include_render.py    MIT License 6 votes vote down vote up
def render_template(self, path, context=None):
        """
        Renders a template in a path.
        :param path: Template path to be rendered. It is relative to this files's directory templates subdirectory.
        :param context: Context dict that will be replaced in that template. By default is empty.
        :return: a rendered template as a string.
        """
        if context is None:
            context = {}
        context = Context(context)

        template_path = os.path.join(self.template_dir, path)

        template_file = open(template_path, "rb")
        template_string = template_file.read()
        return Template(template_string).render(context) 
Example 12
Project: textvisdrg   Author: hds-lab   File: utils.py    MIT License 6 votes vote down vote up
def django_render(template_file, output_file, context):
    """Use the Django template engine to render a template with a context dict"""
    from django.template import Template, Context

    from django.conf import settings

    if not settings.configured:
        settings.configure()

    output_file = _wrap_path(output_file)
    template_file = _wrap_path(template_file)

    if output_file.exists():
        local('mv %s %s.bak' % (output_file, output_file))
        print "Backed up %s file as %s.bak" % (output_file, output_file)

    with open(template_file, 'rb') as infile:
        template = Template(infile.read())

        with open(output_file, 'wb') as outfile:
            outfile.write(template.render(Context(context))) 
Example 13
Project: django-wechat-api   Author: crazy-canux   File: templates.py    GNU General Public License v3.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 14
Project: openhatch   Author: campbe13   File: views.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def suggest_question(request):
    template = "project/suggest_question.html"
    data = {
        'project__pk': request.GET['project__pk']
    }
    return (request, template, data) 
Example 15
Project: openhatch   Author: campbe13   File: views.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def edit_project(request, project__name):
    project = old_project = get_object_or_404(Project, name=project__name)

    if request.POST or request.FILES:
        form = mysite.project.forms.ProjectForm(
            request.POST, request.FILES, instance=project)

        if form.is_valid():
            project = form.save()
            project.update_scaled_icons_from_self_icon()

            # Log that someone has edited the project info.
            logger.info("Project edit: %s just edited a project. The "
                        "project's data originally read as follows: %s. Its"
                        "data now reads as follows: %s" % (request.user.username,
                                                          old_project.__dict__,
                                                          project.__dict__))
            return HttpResponseRedirect(project.get_url())
    else:
        form = mysite.project.forms.ProjectForm(instance=project)

    logger.info("Edit project: setting context and form data")
    context = {'project': project, 'form': form}

    person = request.user.get_profile()
    context['i_am_a_contributor'] = (person in project.get_contributors())
    context['i_described_this_project'] = bool(project.get_pfentries_with_descriptions(person=person))

    pfes = project.get_pfentries_with_descriptions()
    context['pfentries_with_descriptions'] = pfes

    Form = mysite.profile.forms.UseDescriptionFromThisPortfolioEntryForm
    context['pfentry_forms'] = [Form(instance=pfe, prefix=str(pfe.pk)) for pfe in pfes]
    context['trackers'] = project.get_corresponding_bug_trackers()

    return mysite.base.decorators.as_view(request,
                                          template="edit_project.html",
                                          data=context,
                                          slug=__name__) 
Example 16
Project: django-jsx   Author: caktus   File: compilejsx.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def compile_templates(template_list, output=None):
    """
    Write a jsx_registry.js file to output (or stdout if output is None),
    containing boilerplate at top and bottom, and a jsx_registry entry for
    each jsx block found in any of the template files listed in `template_list`.
    :param template_list: A list of template filenames.
    :param output: A file-like object to write to, or None.
    :return: nothing
    """
    print(START_JS, file=output)
    for template in template_list:
        first = True
        try:
            content = open(template).read()
        except IOError:
            pass
        else:
            jsx_blocks = re.findall(R_JSX, content)
            for jsx in jsx_blocks:
                if first:
                    # Add comment indicating the template that these blocks came from.
                    # Can help with debugging.
                    first = False
                    print('/* %s */' % template, file=output)
                hash = hashlib.sha1(jsx.encode('utf-8')).hexdigest()

                jsx = jsx.strip()
                components = set(re.findall(R_COMPONENT, jsx))
                component_statements = []
                # Sort for repeatable output, making for easier debugging and testing
                for component in sorted(components):
                    component_statements.append(
                        "if (Object.hasOwnProperty.call(COMPONENTS, '%(component)s')) "
                        "var {%(component)s} = COMPONENTS;\n" % locals())
                component_statements.append('return (%(jsx)s);' % locals())
                component_statements = ''.join(component_statements)

                print('jsx_registry["%(hash)s"] = '
                      '(COMPONENTS, ctx) => {\n%(component_statements)s\n}' % locals(), file=output)
    print(END_JS, file=output) 
Example 17
Project: ithz   Author: ergoithz   File: template.py    MIT License 5 votes vote down vote up
def load(path, debug=False):
  abspath = os.path.abspath(path)

  if not debug:
    template = template_cache.get(abspath, None)
  else:
    template = None

  if not template:
    directory, file_name = os.path.split(abspath)
    new_settings = {
        'TEMPLATE_DIRS': (directory,),
        'TEMPLATE_DEBUG': debug,
        'DEBUG': debug,
        }
    old_settings = _swap_settings(new_settings)
    try:
      template = django.template.loader.get_template(file_name)
    finally:
      _swap_settings(old_settings)

    if not debug:
      template_cache[abspath] = template

    def wrap_render(context, orig_render=template.render):
      URLNode = django.template.defaulttags.URLNode
      save_urlnode_render = URLNode.render
      old_settings = _swap_settings(new_settings)
      try:
        URLNode.render = _urlnode_render_replacement
        return orig_render(context)
      finally:
        _swap_settings(old_settings)
        URLNode.render = save_urlnode_render

    template.render = wrap_render

  return template 
Example 18
Project: ithz   Author: ergoithz   File: template.py    MIT License 5 votes vote down vote up
def create_template_register():
    return django.template.Library() 
Example 19
Project: ithz   Author: ergoithz   File: template.py    MIT License 5 votes vote down vote up
def register_template_library(package_name):
  if not django.template.libraries.get(package_name, None):
    django.template.add_to_builtins(package_name) 
Example 20
Project: GTDWeb   Author: lanbing510   File: templates.py    GNU General Public License v2.0 5 votes vote down vote up
def add_arguments(self, parser):
        parser.add_argument('name', help='Name of the application or project.')
        parser.add_argument('directory', nargs='?', help='Optional destination directory')
        parser.add_argument('--template',
            help='The path or URL to load the template from.')
        parser.add_argument('--extension', '-e', dest='extensions',
            action='append', default=['py'],
            help='The file extension(s) to render (default: "py"). '
                 'Separate multiple extensions with commas, or use '
                 '-e multiple times.')
        parser.add_argument('--name', '-n', dest='files',
            action='append', default=[],
            help='The file name(s) to render. '
                 'Separate multiple extensions with commas, or use '
                 '-n multiple times.') 
Example 21
Project: GTDWeb   Author: lanbing510   File: templates.py    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 22
Project: pypugjs   Author: akubera   File: test_cases.py    MIT License 5 votes vote down vote up
def jinja_process(src, filename):
        global jinja_env
        template = jinja_env.get_template(filename)
        return template.render() 
Example 23
Project: pypugjs   Author: akubera   File: test_cases.py    MIT License 5 votes vote down vote up
def jinja_process_variable_start_string(src, filename):
        global jinja_env
        template = jinja_env.get_template(filename)
        return template.render() 
Example 24
Project: pypugjs   Author: akubera   File: test_cases.py    MIT License 5 votes vote down vote up
def tornado_process(src, filename):
        global loader, tornado
        template = tornado.template.Template(src, name='_.pug', loader=loader)
        generated = template.generate(missing=None)
        if isinstance(generated, six.binary_type):
            generated = generated.decode("utf-8")
        return generated 
Example 25
Project: pypugjs   Author: akubera   File: test_cases.py    MIT License 5 votes vote down vote up
def django_process(src, filename):
        # actually use the django loader to get the sources
        loader = Loader(
            Engine.get_default(), config['TEMPLATES'][0]['OPTIONS']['loaders']
        )

        t = loader.get_template(filename)
        ctx = django.template.Context()
        return t.render(ctx) 
Example 26
Project: pypugjs   Author: akubera   File: test_cases.py    MIT License 5 votes vote down vote up
def mako_process(src, filename):
        t = mako.template.Template(
            src,
            lookup=dirlookup,
            preprocessor=pypugjs.ext.mako.preprocessor,
            default_filters=['decode.utf8'],
        )
        return t.render() 
Example 27
Project: DCRM   Author: 82Flex   File: fluent_comments_tags.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def render(self, context):
        # Include proper template, avoid parsing it twice by operating like @register.inclusion_tag()
        if not getattr(self, 'nodelist', None):
            if appsettings.USE_THREADEDCOMMENTS:
                template = get_template("fluent_comments/templatetags/threaded_list.html")
            else:
                template = get_template("fluent_comments/templatetags/flat_list.html")
            self.nodelist = template

        # NOTE NOTE NOTE
        # HACK: Determine the parent object based on the comment list queryset.
        # the {% render_comment_list for article %} tag does not pass the object in a general form to the template.
        # Not assuming that 'object.pk' holds the correct value.
        #
        # This obviously doesn't work when the list is empty.
        # To address that, the client-side code also fixes that, by looking for the object ID in the nearby form.
        target_object_id = context.get('target_object_id', None)
        if not target_object_id:
            comment_list = context['comment_list']
            if isinstance(comment_list, list) and comment_list:
                target_object_id = comment_list[0].object_pk

        # Render the node
        context['USE_THREADEDCOMMENTS'] = appsettings.USE_THREADEDCOMMENTS
        context['target_object_id'] = target_object_id

        if django.VERSION >= (1, 8):
            context = context.flatten()
        return self.nodelist.render(context) 
Example 28
Project: DCRM   Author: 82Flex   File: fluent_comments_tags.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def fluent_comments_list(parser, token):
    """
    A tag to select the proper template for the current comments app.
    """
    return FluentCommentsList() 
Example 29
Project: django-seo   Author: whyflyru   File: tests.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_for_obj_no_metadata(self):
        """ Checks that defaults are used when no metadata object (previously) exists.
            The relevant path is also removed so that the object's link to the database is used.
        """
        self.deregister_alternatives()

        # Remove all metadata
        Metadata = Coverage._meta.get_model('modelinstance')

        # Create a page with metadata (with a path that get_metadata won't find)
        page = Page.objects.create(title=u"Page Title", type=u"nometadata", content=u"no meta data")
        content_type = ContentType.objects.get_for_model(Page)
        Metadata.objects.filter(_content_type=content_type, _object_id=page.pk).update(title="Page Title",
                                                                                       _path="/different/")

        expected_output = '<title>Page Title</title>'

        # Check the output of the template is correct when the metadata exists
        self.context = {'obj': page}
        self.compilesTo("{% get_metadata for obj %}", expected_output)
        self.compilesTo("{% get_metadata for obj as var %}{{ var }}", expected_output)
        self.compilesTo("{% get_metadata for obj as var %}{{ var.populate_from7 }}",
                        '<populate_from7>model instance content: no meta data</populate_from7>')

        # Check the output is correct when there is no metadata
        Metadata.objects.filter(_content_type=content_type, _object_id=page.pk).delete()
        self.compilesTo("{% get_metadata for obj %}", "<title>example.com</title>")
        self.compilesTo("{% get_metadata for obj as var %}{{ var }}", "<title>example.com</title>")
        self.compilesTo("{% get_metadata for obj as var %}{{ var.populate_from7 }}",
                        '<populate_from7>model instance content: no meta data</populate_from7>') 
Example 30
Project: django-seo   Author: whyflyru   File: tests.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def compilesTo(self, input, expected_output):
        """ Asserts that the given template string compiles to the given output.
        """
        input = '{% load seo %}' + input
        environ = {
            'PATH_INFO': self.path,
            'REQUEST_METHOD': 'GET',
            'wsgi.input': FakePayload(''),
        }

        # Create a fake request for our purposes
        request = WSGIRequest(environ)
        context = RequestContext(request)
        context.update(self.context)
        self.assertEqual(Template(input).render(context).strip(), expected_output.strip()) 
Example 31
Project: user-profile   Author: 41xu   File: views.py    GNU General Public License v3.0 5 votes vote down vote up
def chart(request):
    if request.method=="POST":
        appid=int(request.POST.get('appid'))
        template=loader.get_template('chart.html')
        age_pie=calage(appid)
        gender_pie=calgender(appid)
        context=dict(
            host=REMOTE_HOST,
            myechart_gender=gender_pie.render_embed(),
            script_list_gender=gender_pie.get_js_dependencies(),
            myechart_age=age_pie.render_embed(),
            script_list_age=age_pie.get_js_dependencies()
        )
        return HttpResponse(template.render(context,request))
    return render_to_response('chart.html') 
Example 32
Project: openode   Author: JvGinkel   File: django_patches.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def render(self, context):
        csrf_token = context.get('csrf_token', None)
        if csrf_token:
            if csrf_token == 'NOTPROVIDED':
                return mark_safe(u"")
            else:
                return mark_safe(u"<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='%s' /></div>" % csrf_token)
        else:
            # It's very probable that the token is missing because of
            # misconfiguration, so we raise a warning
            from django.conf import settings
            if settings.DEBUG:
                import warnings
                warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value.  This is usually caused by not using RequestContext.")
            return u'' 
Example 33
Project: openode   Author: JvGinkel   File: django_patches.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def add_import_library_function():

    #this definition is copy/pasted from django 1.2 source code
    #it is necessary to make Coffin library happy
    from django.utils.importlib import import_module
    class InvalidTemplateLibrary(Exception):
        pass

    def import_library(taglib_module):
        """Load a template tag library module.
        Verifies that the library contains a 'register' attribute, and
        returns that attribute as the representation of the library
        """
        app_path, taglib = taglib_module.rsplit('.',1)
        app_module = import_module(app_path)
        try:
            mod = import_module(taglib_module)
        except ImportError, e:
            # If the ImportError is because the taglib submodule does not exist, that's not
            # an error that should be raised. If the submodule exists and raised an ImportError
            # on the attempt to load it, that we want to raise.
            if not module_has_submodule(app_module, taglib):
                return None
            else:
                raise InvalidTemplateLibrary("ImportError raised loading %s: %s" % (taglib_module, e))
        try:
            return mod.register
        except AttributeError:
            raise InvalidTemplateLibrary("Template library %s does not have a variable named 'register'" % taglib_module) 
Example 34
Project: django-admin-rq   Author: Proper-Job   File: admin.py    MIT License 5 votes vote down vote up
def get_job_form_template(self, job_name, request=None, object_id=None, view_name=None, extra_context=None):
        """
        Returns the template for this job's start page
        """
        return 'django_admin_rq/job_form.html' 
Example 35
Project: django-admin-rq   Author: Proper-Job   File: admin.py    MIT License 5 votes vote down vote up
def get_job_run_template(self, job_name, preview=True, request=None, object_id=None, view_name=None,
                             extra_context=None):
        """
        Returns the template for this job's run page.
        """
        return 'django_admin_rq/job_run.html' 
Example 36
Project: django-admin-rq   Author: Proper-Job   File: admin.py    MIT License 5 votes vote down vote up
def get_job_complete_template(self, job_name, request=None, object_id=None, view_name=None,
                             extra_context=None):
        """
        Returns the template for this job's complete page
        """
        return 'django_admin_rq/job_complete.html' 
Example 37
Project: django-compiling-loader   Author: mhallin   File: run_benchmark.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def switch_loader_settings(new_param):
    from django.conf import settings
    from django.template import loader

    settings.TEMPLATE_LOADERS = new_param
    loader.template_source_loaders = None 
Example 38
Project: django-electron-pdf   Author: namespace-ee   File: utils.py    MIT License 5 votes vote down vote up
def __init__(self, template, context, request=None):
        self.temporary_file = render_to_temporary_file(
            template=template,
            context=context,
            request=request,
            prefix='electron_pdf', suffix='.html',
            delete=(not settings.ELECTRON_PDF_DEBUG)
        )
        self.filename = self.temporary_file.name 
Example 39
Project: django-electron-pdf   Author: namespace-ee   File: utils.py    MIT License 5 votes vote down vote up
def render_pdf_from_template(input_template, context, request=None, cmd_options={}):
    input_file = RenderedFile(
        template=input_template,
        context=context,
        request=request
    )
    return electron_pdf(input_file, **cmd_options) 
Example 40
Project: taiga-back-   Author: andyzsf   File: renderers.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_template_names(self, response, view):
        if response.template_name:
            return [response.template_name]
        elif self.template_name:
            return [self.template_name]
        elif hasattr(view, "get_template_names"):
            return view.get_template_names()
        elif hasattr(view, "template_name"):
            return [view.template_name]
        raise ImproperlyConfigured("Returned a template response with no `template_name` attribute set on either the view or response") 
Example 41
Project: taiga-back-   Author: andyzsf   File: renderers.py    GNU Affero General Public License v3.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"
            return Template("%d %s" % (response.status_code,
                                       response.status_text.title()))


# Note, subclass TemplateHTMLRenderer simply for the exception behavior 
Example 42
Project: taiga-back-   Author: andyzsf   File: renderers.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def render(self, data, accepted_media_type=None, renderer_context=None):
        renderer_context = renderer_context or {}
        response = renderer_context["response"]

        if response and response.exception:
            request = renderer_context["request"]
            template = self.get_exception_template(response)
            context = self.resolve_context(data, request, response)
            return template.render(context)

        return data 
Example 43
Project: taiga-back-   Author: andyzsf   File: renderers.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        Render serializer data and return an HTML form, as a string.
        """
        renderer_context = renderer_context or {}
        request = renderer_context["request"]

        template = loader.get_template(self.template)
        context = RequestContext(request, {"form": data})
        return template.render(context) 
Example 44
Project: fluentcms-contactform   Author: django-fluent   File: email.py    Apache License 2.0 5 votes vote down vote up
def get_email_context(self, form, **extra_context):
        """
        Generate the context data for the template
        """
        db_data = form.instance
        context = {
            'request': self.request,
            'site': self.site,
            'db_data': db_data,
            'admin_form_data_url': self.get_admin_url(db_data),
            'form_data': form.get_field_summary(),
        }
        context.update(extra_context)
        return context 
Example 45
Project: fluentcms-contactform   Author: django-fluent   File: email.py    Apache License 2.0 5 votes vote down vote up
def render_txt_template(template_name, context):
    """
    Render a plain text template without escaping variables to HTML.

    .. note::
        This is only supported for Django 1.10 and below,
        thus exists for backwards compatibility.
    """
    if django.VERSION >= (1, 10):
        # Can't disable autoescaping anymore!
        # It's a backend engine setting now.
        return render_to_string(template_name, context)
    else:
        # For backwards compatibility
        return render_to_string(template_name, context, context_instance=Context(autoescape=False)) 
Example 46
Project: django-leonardo   Author: django-leonardo   File: shortcuts_patch.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render(request, *args, **kwargs):
        """
        Returns a HttpResponse whose content is filled with the result of calling
        django.template.loader.render_to_string() with the passed arguments.
        Uses a RequestContext by default.
        """
        httpresponse_kwargs = {
            'content_type': kwargs.pop('content_type', None),
            'status': kwargs.pop('status', None),
        }

        if hasattr(request, '_feincms_extra_context') and 'widget' in request._feincms_extra_context:
            if 'context' in kwargs:
                kwargs['context'][
                    'widget'] = request._feincms_extra_context['widget']

        if 'context_instance' in kwargs:
            context_instance = kwargs.pop('context_instance')
            if kwargs.get('current_app', None):
                raise ValueError('If you provide a context_instance you must '
                                 'set its current_app before calling render()')
        else:
            current_app = kwargs.pop('current_app', None)
            context_instance = RequestContext(request, current_app=current_app)

        kwargs['context_instance'] = context_instance

        return HttpResponse(loader.render_to_string(*args, **kwargs),
                            **httpresponse_kwargs) 
Example 47
Project: django-leonardo   Author: django-leonardo   File: shortcuts_patch.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render(request, template_name, context={}, content_type=None, status=None, using=None):
        """
        Returns a HttpResponse whose content is filled with the result of calling
        django.template.loader.render_to_string() with the passed arguments.
        """

        if hasattr(request, '_feincms_extra_context') and 'widget' in request._feincms_extra_context:
            context['widget'] = request._feincms_extra_context['widget']
        content = loader.render_to_string(
            template_name, context, request, using=using)
        return HttpResponse(content, content_type, status) 
Example 48
Project: luscan-devel   Author: blackye   File: templates.py    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 49
Project: django-popup-view-field   Author: djk2   File: widgets.py    MIT License 5 votes vote down vote up
def render(self, name, value, attrs=None, **kwargs):
        value = value or ''
        context = self.get_context(name, value, attrs)

        if django.VERSION < (1, 11):
            template = loader.get_template(self.template_name)
            return template.render(context).strip()

        else:
            return super(PopupViewWidget, self).render(name, value, attrs, **kwargs) 
Example 50
Project: wagtailmodeladmin   Author: rkhleics   File: wagtailmodeladmin_tags.py    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,
    })