Python django.template.base.Template() Examples

The following are 15 code examples of django.template.base.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.template.base , or try the search function .
Example #1
Source File: send_letter_email.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def send_letter_email(request, grad_slug, letter_slug):
    letter = get_object_or_404(Letter, slug=letter_slug)
    grad = get_object_or_404(GradStudent, person=letter.student.person, slug=grad_slug, program__unit__in=request.units)
    if request.method == 'POST':
        form = LetterEmailForm(request.POST)
        if form.is_valid():
            letter.set_email_body(form.cleaned_data['email_body'])
            letter.set_email_subject(form.cleaned_data['email_subject'])
            if 'email_cc' in form.cleaned_data:
                letter.set_email_cc(form.cleaned_data['email_cc'])
            letter.set_email_sent(timezone_today())
            letter.save()
            return _send_letter(request, grad_slug, letter)

    else:
        email_template = letter.template.email_body()
        temp = Template(email_template)
        ls = grad.letter_info()
        text = temp.render(Context(ls))
        form = LetterEmailForm(initial={'email_body': text, 'email_subject': letter.template.email_subject()})
    return render(request, 'grad/select_letter_email_text.html', {'form': form, 'grad': grad, 'letter': letter}) 
Example #2
Source File: cached.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def load_template(self, template_name, template_dirs=None):
        key = self.cache_key(template_name, template_dirs)
        template_tuple = self.template_cache.get(key)
        # A cached previous failure:
        if template_tuple is TemplateDoesNotExist:
            raise TemplateDoesNotExist
        elif template_tuple is None:
            template, origin = self.find_template(template_name, template_dirs)
            if not hasattr(template, 'render'):
                try:
                    template = Template(template, origin, template_name, self.engine)
                except TemplateDoesNotExist:
                    # If compiling the template we found raises TemplateDoesNotExist,
                    # back off to returning the source and display name for the template
                    # we were asked to load. This allows for correct identification (later)
                    # of the actual template that does not exist.
                    self.template_cache[key] = (template, origin)
            self.template_cache[key] = (template, None)
        return self.template_cache[key] 
Example #3
Source File: base.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def load_template(self, template_name, template_dirs=None):
        source, display_name = self.load_template_source(
            template_name, template_dirs)
        origin = self.engine.make_origin(
            display_name, self.load_template_source,
            template_name, template_dirs)

        try:
            template = Template(source, origin, template_name, self.engine)
        except TemplateDoesNotExist:
            # If compiling the template we found raises TemplateDoesNotExist,
            # back off to returning the source and display name for the
            # template we were asked to load. This allows for correct
            # identification of the actual template that does not exist.
            return source, display_name
        else:
            return template, None 
Example #4
Source File: views.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def get_memo_text(request, userid, event_slug, memo_template_id):
    """ Get the text from memo template """
    person, member_units = _get_faculty_or_404(request.units, userid)
    event = _get_event_or_404(units=request.units, slug=event_slug, person=person)
    lt = get_object_or_404(MemoTemplate, id=memo_template_id, unit__in=Unit.sub_units(request.units))
    temp = Template(lt.template_text)
    ls = event.memo_info()
    text = temp.render(Context(ls))

    return HttpResponse(text, content_type='text/plain') 
Example #5
Source File: get_letter_text.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def get_letter_text(request, grad_slug, letter_template_id):
    """ Get the text from letter template """
    grad = get_object_or_404(GradStudent, slug=grad_slug, program__unit__in=request.units)
    lt = get_object_or_404(LetterTemplate, id=letter_template_id, unit__in=request.units)
    temp = Template(lt.content)
    ls = grad.letter_info()
    text = temp.render(Context(ls))
    #print ls

    return HttpResponse(text, content_type='text/plain') 
Example #6
Source File: css_inliner.py    From cornerwise with MIT License 5 votes vote down vote up
def rebuild_template(template_str):
    nodes = Template(template_str).compile_nodelist()
    expanded = expand_includes(nodes)
    tree = lxml.html.fromstring(nodelist_to_template(expanded))
    links_to_style(tree)
    toronado.inline(tree)

    return lxml.html.tostring(tree)

# body = urlopen("http://localhost:4000").read()
# tree = lxml.html.fromstring(body) 
Example #7
Source File: tests.py    From django-apptemplates with MIT License 5 votes vote down vote up
def test_render():
    """
    Test-drive the apptemplate code base by rendering a template.
    """
    c = Context()
    t = Template('{% extends "admin:admin/base.html" %}')
    t.render(c) 
Example #8
Source File: tests.py    From django-apptemplates with MIT License 5 votes vote down vote up
def test_cached():
    """
    Test that the template still works when the cached loader is being used.
    """
    c = Context()
    t = Template('{% extends "admin:admin/base.html" %}')
    t.render(c) 
Example #9
Source File: preview.py    From ontask_b with MIT License 5 votes vote down vote up
def _evaluate_row_action_in(action: models.Action, context: Mapping):
    """Evaluate an action_in in the given context.

    Given an action IN object and a row index:
    1) Create the form and the context
    2) Run the template with the context
    3) Return the resulting object (HTML?)

    :param action: Action object.
    :param context: Dictionary with pairs name/value
    :return: String with the HTML content resulting from the evaluation
    """
    # Get the active columns attached to the action
    tuples = [
        column_condition_pair
        for column_condition_pair in action.column_condition_pair.all()
        if column_condition_pair.column.is_active
    ]

    col_values = [context[colcon_pair.column.name] for colcon_pair in tuples]

    form = forms.EnterActionIn(
        None,
        tuples=tuples,
        context=context,
        values=col_values)

    # Render the form
    return Template(
        """<div align="center">
             <p class="lead">{{ description_text }}</p>
             {% load crispy_forms_tags %}{{ form|crispy }}
           </div>""",
    ).render(Context(
        {
            'form': form,
            'description_text': action.description_text,
        },
    )) 
Example #10
Source File: loader.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def get_template(template_name):
    """
    Returns a compiled Template object for the given template name,
    handling template inheritance recursively.
    """
    template, origin = find_template(template_name)
    if not hasattr(template, 'render'):
        # template needs to be compiled
        template = get_template_from_string(template, origin, template_name)
    return template 
Example #11
Source File: loader.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def get_template_from_string(source, origin=None, name=None):
    """
    Returns a compiled Template object for the given template code,
    handling template inheritance recursively.
    """
    return Template(source, origin, name) 
Example #12
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 #13
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def add_service(request, username, id_string):
    data = {}
    form = RestServiceForm()
    xform = get_object_or_404(
        XForm, user__username__iexact=username, id_string__exact=id_string)
    if request.method == 'POST':
        form = RestServiceForm(request.POST)
        restservice = None
        if form.is_valid():
            service_name = form.cleaned_data['service_name']
            service_url = form.cleaned_data['service_url']
            try:
                rs = RestService(service_url=service_url,
                                 name=service_name, xform=xform)
                rs.save()
            except IntegrityError:
                message = _(u"Service already defined.")
                status = 'fail'
            else:
                status = 'success'
                message = (_(u"Successfully added service %(name)s.")
                           % {'name': service_name})
                service_tpl = render_to_string("service.html", {
                    "sv": rs, "username": xform.user.username,
                    "id_string": xform.id_string})
                restservice = service_tpl
        else:
            status = 'fail'
            message = _(u"Please fill in all required fields")

            if form.errors:
                for field in form:
                    message += Template(u"{{ field.errors }}")\
                        .render(Context({'field': field}))
        if request.is_ajax():
            response = {'status': status, 'message': message}
            if restservice:
                response["restservice"] = u"%s" % restservice

            return HttpResponse(json.dumps(response))

        data['status'] = status
        data['message'] = message

    data['list_services'] = RestService.objects.filter(xform=xform)
    data['form'] = form
    data['username'] = username
    data['id_string'] = id_string

    return render(request, "add-service.html", data) 
Example #14
Source File: utils.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def iterate_with_template_sources(
    frames,
    with_locals=True,
    library_frame_context_lines=None,
    in_app_frame_context_lines=None,
    include_paths_re=None,
    exclude_paths_re=None,
    locals_processor_func=None,
):
    template = None
    for f in frames:
        try:
            frame, lineno = f
        except ValueError:
            # TODO how can we possibly get anything besides a (frame, lineno) tuple here???
            logging.getLogger("elasticapm").error("Malformed list of frames. Frames may be missing in Kibana.")
            break
        f_code = getattr(frame, "f_code", None)
        if f_code:
            function_name = frame.f_code.co_name
            if function_name == "render":
                renderer = getattr(frame, "f_locals", {}).get("self")
                if renderer and isinstance(renderer, Node):
                    if getattr(renderer, "token", None) is not None:
                        if hasattr(renderer, "source"):
                            # up to Django 1.8
                            yield {"lineno": renderer.token.lineno, "filename": renderer.source[0].name}
                        else:
                            template = {"lineno": renderer.token.lineno}
                # Django 1.9 doesn't have the origin on the Node instance,
                # so we have to get it a bit further down the stack from the
                # Template instance
                elif renderer and isinstance(renderer, Template):
                    if template and getattr(renderer, "origin", None):
                        template["filename"] = renderer.origin.name
                        yield template
                        template = None

        yield get_frame_info(
            frame,
            lineno,
            library_frame_context_lines=library_frame_context_lines,
            in_app_frame_context_lines=in_app_frame_context_lines,
            with_locals=with_locals,
            include_paths_re=include_paths_re,
            exclude_paths_re=exclude_paths_re,
            locals_processor_func=locals_processor_func,
        ) 
Example #15
Source File: plugin.py    From django_coverage_plugin with Apache License 2.0 4 votes vote down vote up
def line_number_range(self, frame):
        assert frame.f_code.co_name == 'render'
        if 0:
            dump_frame(frame, label="line_number_range")

        render_self = frame.f_locals['self']
        if isinstance(render_self, (NodeList, Template)):
            return -1, -1

        position = position_for_node(render_self)
        if position is None:
            return -1, -1

        if SHOW_TRACING:
            print("{!r}: {}".format(render_self, position))
        s_start, s_end = position
        if isinstance(render_self, TextNode):
            first_line = render_self.s.splitlines(True)[0]
            if first_line.isspace():
                s_start += len(first_line)
        elif VerbatimNode and isinstance(render_self, VerbatimNode):
            # VerbatimNode doesn't track source the same way. s_end only points
            # to the end of the {% verbatim %} opening tag, not the entire
            # content. Adjust it to cover all of it.
            s_end += len(render_self.content)
        elif isinstance(render_self, BlockTranslateNode):
            # BlockTranslateNode has a list of text and variable tokens.
            # Get the end of the contents by looking at the last token,
            # and use its endpoint.
            last_tokens = render_self.plural or render_self.singular
            s_end = position_for_token(last_tokens[-1])[1]

        filename = filename_for_frame(frame)
        line_map = self.get_line_map(filename)
        start = get_line_number(line_map, s_start)
        end = get_line_number(line_map, s_end-1)
        if start < 0 or end < 0:
            start, end = -1, -1
        if SHOW_TRACING:
            print("line_number_range({}) -> {}".format(
                filename, (start, end)
            ))
        return start, end

    # --- FileTracer helpers