Python django.template.Template() Examples

The following are 30 code examples of django.template.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 , or try the search function .
Example #1
Source File: views.py    From coursys with GNU General Public License v3.0 7 votes vote down vote up
def view_email_preview(request, alert_type, alert_id, automation_id):
    alert_email = get_object_or_404(AlertEmailTemplate, id=automation_id)
    alert_type = get_object_or_404(AlertType, slug=alert_type, unit__in=request.units)
    alert = get_object_or_404(Alert, pk=alert_id, alerttype__unit__in=request.units)

    t = Template( alert_email.content )

    email_context = build_context( alert )    
    email_context['details'] = {}
    for k, v in alert.details.items():
        email_context['details'][k] = str(v)

    rendered_text = t.render( Context(email_context) ) 
    
    return render(request, 'alerts/view_email_preview.html', { 'alert_type':alert_type, 
                                                                'alert':alert, 
                                                                'alert_email':alert_email, 
                                                                'rendered_text':rendered_text }) 
Example #2
Source File: test_all.py    From DCRM with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_preferences_cp(self):
        request = RequestFactory().get('/')
        context = context_processors.preferences_cp(request)

        # context should have preferences.
        my_preferences = context['preferences']

        # preferences should have test MyPreferences object member.
        my_preferences = my_preferences.MyPreferences
        self.failUnless(isinstance(my_preferences, MyPreferences),
                        "%s should be instance of MyPreferences." % my_preferences)

        # With preferences_cp is loaded as a TEMPLATE_CONTEXT_PROCESSORS
        # templates should have access to preferences object.
        context_instance = RequestContext(request)
        t = Template("{% if preferences %}{{ preferences }}{% endif %}")
        self.failUnless(t.render(context_instance), "preferences should be \
available in template context.")

        t = Template("{% if preferences.MyPreferences %}{{ \
preferences.MyPreferences }}{% endif %}")
        self.failUnless(t.render(context_instance), "MyPreferences should be \
available as part of preferences var in template context.") 
Example #3
Source File: test_templatetags.py    From django-connections with MIT License 6 votes vote down vote up
def test_get_connection_distance(self):
        tpl = """{%% spaceless %%}
            {%% load connections %%}
            {%% get_connection_distance %s foo bar as distance %%}
            {{ distance }}
        {%% endspaceless %%}"""
        
        create_connection(self.r, self.foo, self.bar)
        
        assert '1' == Template(tpl % "'user_follow'").render(Context({
            'foo': self.foo,
            'bar': self.bar,
        }))
        
        assert '1' == Template(tpl % "rel").render(Context({
            'rel': self.r,
            'foo': self.foo,
            'bar': self.bar,
        })) 
Example #4
Source File: test_templatetags.py    From django-connections with MIT License 6 votes vote down vote up
def test_connections_from_object(self):
        tpl = """{%% spaceless %%}
            {%% load connections %%}
            {%% connections_from_object %s foo as connections %%}
            {%% for c in connections %%}{{ c.to_object.username }}, {%% endfor %%}
        {%% endspaceless %%}"""
        
        create_connection(self.r, self.foo, self.bar)
        create_connection(self.r, self.foo, self.jaz)
        
        assert 'bar, jaz,' == Template(tpl % "'user_follow'").render(Context({
            'foo': self.foo,
        }))
        
        assert 'bar, jaz,' == Template(tpl % "rel").render(Context({
            'rel': self.r,
            'foo': self.foo,
        })) 
Example #5
Source File: test_templatetags.py    From django-connections with MIT License 6 votes vote down vote up
def test_connections_to_object(self):
        tpl = """{%% spaceless %%}
            {%% load connections %%}
            {%% connections_to_object %s foo as connections %%}
            {%% for c in connections %%}{{ c.from_object.username }}, {%% endfor %%}
        {%% endspaceless %%}"""
        
        create_connection(self.r, self.bar, self.foo)
        create_connection(self.r, self.jaz, self.foo)
        
        assert 'bar, jaz,' == Template(tpl % "'user_follow'").render(Context({
            'foo': self.foo,
        }))
        
        assert 'bar, jaz,' == Template(tpl % "rel").render(Context({
            'rel': self.r,
            'foo': self.foo,
        })) 
Example #6
Source File: base.py    From bioforum with MIT License 6 votes vote down vote up
def get_template(self, template_name, skip=None):
        """
        Call self.get_template_sources() and return a Template object for
        the first template matching template_name. If skip is provided, ignore
        template origins in skip. This is used to avoid recursion during
        template extending.
        """
        tried = []

        for origin in self.get_template_sources(template_name):
            if skip is not None and origin in skip:
                tried.append((origin, 'Skipped'))
                continue

            try:
                contents = self.get_contents(origin)
            except TemplateDoesNotExist:
                tried.append((origin, 'Source does not exist'))
                continue
            else:
                return Template(
                    contents, origin, origin.template_name, self.engine,
                )

        raise TemplateDoesNotExist(template_name, tried=tried) 
Example #7
Source File: editable.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def get(self, request, object_id):
        model_fields = [f.name for f in self.opts.fields]
        fields = [f for f in request.GET['fields'].split(',') if f in model_fields]
        defaults = {
            "form": self.form,
            "fields": fields,
            "formfield_callback": self.formfield_for_dbfield,
        }
        form_class = modelform_factory(self.model, **defaults)
        form = form_class(instance=self.org_obj)

        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        form.helper = helper

        s = '{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% crispy form %}' + \
            '<button type="submit" class="btn btn-success btn-block btn-sm">{% trans "Apply" %}</button></form>'
        t = template.Template(s)
        c = template.Context({'form': form, 'action_url': self.model_admin_url('patch', self.org_obj.pk)})

        return HttpResponse(t.render(c)) 
Example #8
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 #9
Source File: route_view.py    From jet-bridge with MIT License 6 votes vote down vote up
def write_response(self, response):
        if isinstance(response, RedirectResponse):
            result = HttpResponseRedirect(response.url, status=response.status)
        elif isinstance(response, OptionalJSONResponse) and isinstance(response.data, HttpResponseBase):
            result = response.data
        elif isinstance(response, TemplateResponse):
            template_path = os.path.join(base_settings.BASE_DIR, 'templates', response.template)
            with open(template_path, 'r') as file:
                template = file.read()
                template = template.replace('{% end %}', '{% endif %}')
                context = Context(response.data)
                content = Template(template).render(context)
                result = HttpResponse(content, status=response.status)
        else:
            result = HttpResponse(response.render(), status=response.status)

        for name, value in self.view.default_headers().items():
            result[name] = value

        for name, value in response.header_items():
            result[name] = value

        return result 
Example #10
Source File: test_templatetags.py    From django-connections with MIT License 6 votes vote down vote up
def test_connection_exists(self):
        tpl = """{%% spaceless %%}
            {%% load connections %%}
            {%% connection_exists %s foo bar as has_connection %%}
            {{ has_connection|yesno:'True,False' }}
        {%% endspaceless %%}"""
        
        create_connection(self.r, self.foo, self.bar)
        
        assert 'True' == Template(tpl % "'user_follow'").render(Context({
            'foo': self.foo,
            'bar': self.bar,
        }))
        
        assert 'True' == Template(tpl % "rel").render(Context({
            'rel': self.r,
            'foo': self.foo,
            'bar': self.bar,
        })) 
Example #11
Source File: tags.py    From wagtail-tag-manager with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_doc(self, request=None, context=None):
        content = self.content

        if request:
            template = Template(content)
            context = Context(Tag.create_context(request, context))
            content = template.render(context)

        return BeautifulSoup(content, "html.parser") 
Example #12
Source File: tests.py    From django-imgix with ISC License 5 votes vote down vote up
def render_template(self, string, context=None):
        context = context or {}
        context = Context(context)
        return Template(string).render(context) 
Example #13
Source File: backends.py    From django-seo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _resolve_template(value, model_instance=None, context=None):
        """ Resolves any template references in the given value. """
        if isinstance(value, six.string_types) and "{" in value:
            if context is None:
                context = Context()
            if model_instance is not None:
                context[model_instance._meta.model_name] = model_instance
            value = Template(value).render(context)
        return value 
Example #14
Source File: test_templatetags.py    From django-bleach with MIT License 5 votes vote down vote up
def test_bleaching_tags(self):
        """ Test provided tags are kept """
        context = Context(
            {'some_unsafe_content': '<script>alert("Hello World!")</script>'}
        )
        template_to_render = Template(
            '{% load bleach_tags %}'
            '{{ some_unsafe_content|bleach:"script" }}'
        )
        rendered_template = template_to_render.render(context)
        self.assertInHTML(
            '<script>alert("Hello World!")</script>', rendered_template
        ) 
Example #15
Source File: test_templatetags.py    From django-bleach with MIT License 5 votes vote down vote up
def test_linkify(self):
        """ Test bleach linkify """
        url = 'www.google.com'
        context = Context({'link_this': url})
        template_to_render = Template(
            '{% load bleach_tags %}'
            '{{ link_this|bleach_linkify|safe }}'
        )
        rendered_template = template_to_render.render(context)
        self.assertInHTML(
            '<a href="http://{0}" rel="nofollow">{0}</a>'.format(url),
            rendered_template
        ) 
Example #16
Source File: test_templatetags.py    From django-bleach with MIT License 5 votes vote down vote up
def test_linkify_none(self):
        """ Test bleach linkify with None as an input """
        context = Context({'none_value': None})
        template_to_render = Template(
            '{% load bleach_tags %}'
            '{{ none_value|bleach_linkify }}'
        )
        rendered_template = template_to_render.render(context)
        self.assertEqual(
            'None',
            rendered_template
        ) 
Example #17
Source File: django_helpers.py    From apis-client-generator with Apache License 2.0 5 votes vote down vote up
def DjangoTemplate(source):
  """Returns a template configured for our default engine.

  Args:
    source: (str) Template source.
  Returns:
    (django.template.Template)
  """
  return django_template.Template(source, engine=_ENGINE) 
Example #18
Source File: tests.py    From django-simple-pagination with MIT License 5 votes vote down vote up
def test_addition(self):
        t = Template(
            "{% load paginate %}{% paginate entities %}.{% show_pageitems %} {% paginate 20 entities %} {% show_pages %}")
        req = HttpRequest()
        c = Context({"entities": range(100), 'request': req})
        val = t.render(c)
        self.assertTrue(bool(val)) 
Example #19
Source File: tags.py    From wagtail-tag-manager with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def clean(self):
        if not re.match(r"\<.+\/?\>", self.content):
            self.content = "<script>{}</script>".format(self.content)

        self.content = BeautifulSoup(self.content, "html.parser").prettify()

        try:
            template = Template(self.content)
            template.render(Context())
        except Exception as error:
            raise ValidationError({"content": error})

        return self 
Example #20
Source File: common.py    From anytask with MIT License 5 votes vote down vote up
def render_mail(message, user):
    if message.variable:
        t = Template(message.text.replace('%', '&#37;'))
        c = Context({
            "last_name": user.last_name,
            "first_name": user.first_name,
        })
        return t.render(c)
    return message.text 
Example #21
Source File: test_compat.py    From django-compat with MIT License 5 votes vote down vote up
def test_verbatim_tag01(self):
        template = Template(self.import_tag +
            '{% verbatim %}{{ bare }}{% endverbatim %}'
        )
        html = template.render(Context({}))
        self.assertEqual(html,
             '{{ bare }}'
        ) 
Example #22
Source File: tests.py    From django-imgix with ISC License 5 votes vote down vote up
def render_template(string, context=None):
        context = context or {}
        context = Context(context)
        return Template(string).render(context) 
Example #23
Source File: __init__.py    From FIR with GNU General Public License v3.0 5 votes vote down vote up
def prepare(template_object, instance, extra_context=None):
        """
        Renders a notification template (subject, description, short description) for a given instance
        which fired an event
        """
        if extra_context is None:
            extra_context = {}
        extra_context.update({'instance': instance})
        context = Context(extra_context)
        return {
            'subject': Template(getattr(template_object, 'subject', "")).render(context),
            'short_description': Template(getattr(template_object, 'short_description', "")).render(context),
            'description': Template(getattr(template_object, 'description', "")).render(context)
        } 
Example #24
Source File: views.py    From FIR with GNU General Public License v3.0 5 votes vote down vote up
def new_event(request):
    if request.method == 'POST':
        form = IncidentForm(request.POST, for_user=request.user)

        form.status = _('Open')

        if form.is_valid():
            i = form.save(commit=False)

            if not form.cleaned_data['is_major']:
                i.is_major = form.cleaned_data['category'].is_major

            if i.is_major:
                i.is_incident = True

            i.opened_by = request.user
            i.save()
            form.save_m2m()
            i.refresh_main_business_lines()
            i.done_creating()

            if i.is_incident:
                return redirect("incidents:details", incident_id=i.id)
            else:
                return redirect("events:details", incident_id=i.id)

    else:
        template = request.GET.get('template', 'default')
        try:
            template = IncidentTemplate.objects.get(name=template)
            data = model_to_dict(template)
            data['description'] = Template(data['description']).render(RequestContext(request))
        except ObjectDoesNotExist:
            data = {}
        form = IncidentForm(initial=data, for_user=request.user)

    return render(request, 'events/new.html', {'form': form, 'mode': 'new'}) 
Example #25
Source File: views.py    From nplusone with MIT License 5 votes vote down vote up
def prefetch_many_to_many_render(request):
    users = models.User.objects.all().prefetch_related('hobbies')
    template = '''
    {% for user in users %}
        {% for hobby in user.hobbies.all %}
            {{ hobby.id }}
        {% endfor %}
    {% endfor %}
    '''
    resp = Template(template).render(Context({'users': users}))
    return HttpResponse(resp) 
Example #26
Source File: response.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _resolve_template(self, template):
        # This wrapper deprecates returning a django.template.Template in
        # subclasses that override resolve_template. It can be removed in
        # Django 1.10.
        new_template = self.resolve_template(template)
        if isinstance(new_template, Template):
            warnings.warn(
                "{}.resolve_template() must return a backend-specific "
                "template like those created by get_template(), not a "
                "{}.".format(
                    self.__class__.__name__, new_template.__class__.__name__),
                RemovedInDjango110Warning, stacklevel=2)
            new_template = BackendTemplate(new_template)
        return new_template 
Example #27
Source File: response.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, template, context=None, content_type=None, status=None,
                 charset=None, using=None):
        if isinstance(template, Template):
            warnings.warn(
                "{}'s template argument cannot be a django.template.Template "
                "anymore. It may be a backend-specific template like those "
                "created by get_template().".format(self.__class__.__name__),
                RemovedInDjango110Warning, stacklevel=2)
            template = BackendTemplate(template)

        # It would seem obvious to call these next two members 'template' and
        # 'context', but those names are reserved as part of the test Client
        # API. To avoid the name collision, we use different names.
        self.template_name = template
        self.context_data = context

        self.using = using

        self._post_render_callbacks = []

        # _request stores the current request object in subclasses that know
        # about requests, like TemplateResponse. It's defined in the base class
        # to minimize code duplication.
        # It's called self._request because self.request gets overwritten by
        # django.test.client.Client. Unlike template_name and context_data,
        # _request should not be considered part of the public API.
        self._request = None

        # content argument doesn't make sense here because it will be replaced
        # with rendered template so we always pass empty string in order to
        # prevent errors and provide shorter signature.
        super(SimpleTemplateResponse, self).__init__('', content_type, status, charset)

        # _is_rendered tracks whether the template and context has been baked
        # into a final response.
        # Super __init__ doesn't know any better than to set self.content to
        # the empty string we just gave it, which wrongly sets _is_rendered
        # True, so we initialize it to False after the call to super __init__.
        self._is_rendered = False 
Example #28
Source File: test_templatetags.py    From django-badgify with MIT License 5 votes vote down vote up
def test_with_user(self):
        badges = badges_tag(**{'user': self.user})
        self.assertEqual(len(badges), 1)
        template = Template('''
            {% load badgify_tags %}
            {% badgify_badges user=user as badges %}
            {% for badge in badges %}{{ badge.name }} {{ badge.slug }}{% endfor %}
        ''')
        rendered = template.render(Context({'user': self.user}))
        self.assertIn(self.badge.name, rendered)
        self.assertIn(self.badge.slug, rendered) 
Example #29
Source File: test_templatetags.py    From django-badgify with MIT License 5 votes vote down vote up
def test_with_username(self):
        badges = badges_tag(**{'username': 'johndoe'})
        self.assertEqual(len(badges), 1)
        template = Template('''
            {% load badgify_tags %}
            {% badgify_badges username="johndoe" as badges %}
            {% for badge in badges %}{{ badge.name }} {{ badge.slug }}{% endfor %}
        ''')
        rendered = template.render(Context({}))
        self.assertIn(self.badge.name, rendered)
        self.assertIn(self.badge.slug, rendered) 
Example #30
Source File: test_templatetags.py    From django-badgify with MIT License 5 votes vote down vote up
def test_no_args(self):
        badges = badges_tag()
        self.assertEqual(len(badges), 20)
        template = Template('''
            {% load badgify_tags %}
            {% badgify_badges as badges %}
            {% for badge in badges %}{{ badge.name }} {{ badge.slug }}{% endfor %}
        ''')
        rendered = template.render(Context({}))
        for badge in self.badges:
            self.assertIn(badge.name, rendered)
            self.assertIn(badge.slug, rendered)