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 Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 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 Project: StormOnline   Author: stormsha   File: editable.py    License: 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 #3
Source Project: DCRM   Author: 82Flex   File: test_all.py    License: 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 #4
Source Project: bioforum   Author: reBiocoder   File: base.py    License: 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 #5
Source Project: django-compat   Author: arteria   File: test_compat.py    License: 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 #6
Source Project: django-connections   Author: dfunckt   File: test_templatetags.py    License: 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 #7
Source Project: django-connections   Author: dfunckt   File: test_templatetags.py    License: 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 #8
Source Project: django-connections   Author: dfunckt   File: test_templatetags.py    License: 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 #9
Source Project: django-connections   Author: dfunckt   File: test_templatetags.py    License: 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 #10
Source Project: jet-bridge   Author: jet-admin   File: route_view.py    License: 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 #11
Source Project: Servo   Author: fpsw   File: note.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def render_template(request, order_id=None):
    """
    Renders the template with this title with the current
    Service Order as the context
    """
    title = request.POST.get('title')
    tpl = get_object_or_404(Template, title=title)
    content = tpl.content

    if order_id:
        order = get_object_or_404(Order, pk=order_id)
        content = tpl.render(order)

    return HttpResponse(content) 
Example #12
Source Project: Servo   Author: fpsw   File: note.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def templates(request, template_id=None):
    if template_id:
        tpl = get_object_or_404(Template, pk=template_id)
        content = tpl.content
        if request.session.get('current_order_id'):
            tpl = template.Template(content)
            order = Order.objects.get(pk=request.session['current_order_id'])
            content = tpl.render(template.Context({'order': order}))

        return HttpResponse(content)

    templates = Template.objects.all()
    return render(request, 'notes/templates.html', {'templates': templates}) 
Example #13
Source Project: Servo   Author: fpsw   File: admin.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean_content(self):
        content = self.cleaned_data.get('content')
        try:
            template.Template(content)
        except template.TemplateSyntaxError, e:
            raise forms.ValidationError(_('Syntax error in template: %s') % e) 
Example #14
Source Project: Servo   Author: fpsw   File: common.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def templates(self):
        choices = Template.objects.all().values_list('title', flat=True)
        return list(choices) 
Example #15
Source Project: Servo   Author: fpsw   File: common.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def render(self, context):
        from django import template
        tpl = template.Template(self.content)
        return tpl.render(template.Context({'order': context})) 
Example #16
Source Project: edx_xblock_scorm   Author: raccoongang   File: scormxblock.py    License: Apache License 2.0 5 votes vote down vote up
def render_template(self, template_path, context):
        template_str = self.resource_string(template_path)
        template = Template(template_str)
        return template.render(Context(context)) 
Example #17
Source Project: OpenMDM   Author: OpenMDM   File: tests.py    License: Apache License 2.0 5 votes vote down vote up
def test_basic_form(self):
        form = ExampleForm()

        html = Template("{% load bootstrap %}{{ form|bootstrap }}").render(Context({'form': form}))

        tpl = os.path.join('fixtures', 'basic.html')
        with open(os.path.join(TEST_DIR, tpl)) as f:
            content = f.read()

        self.assertHTMLEqual(html, content) 
Example #18
Source Project: OpenMDM   Author: OpenMDM   File: tests.py    License: Apache License 2.0 5 votes vote down vote up
def test_horizontal_form(self):
        form = ExampleForm()

        html = Template("{% load bootstrap %}{{ form|bootstrap_horizontal }}").render(Context({'form': form}))

        tpl = os.path.join('fixtures', 'horizontal.html')
        with open(os.path.join(TEST_DIR, tpl)) as f:
            content = f.read()

        self.assertHTMLEqual(html, content) 
Example #19
Source Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def test_retrieve_get_param(self):
        out = Template(
            "{% load url_tags %}"
            "{% get_parameters %}"
        ).render(RequestContext(self.request, {}))
        self.assertTrue(out == "page=3&sort=asc" or out == "sort=asc&page=3") 
Example #20
Source Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def test_except_fields(self):
        out = Template(
            "{% load url_tags %}"
            "{% get_parameters 'sort' %}"
        ).render(RequestContext(self.request, {}))
        self.assertEqual(out, "page=3") 
Example #21
Source Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def test_text_field_class_name(self):
        out = Template(
            "{% load form_filters %}"
            "{% for field in form %}"
            "{{ field|css_class }},"
            "{% endfor %}"
        ).render(Context({
            'form': self.form
        }))
        self.assertEqual(out, "textinput,dateinput,") 
Example #22
Source Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def test_simple_times_filter_loop(self):
        out = Template(
            "{% load my_filters %}"
            "{% for i in 5|times %}"
            "{{ i }},"
            "{% endfor %}"
        ).render(Context())
        self.assertEqual(out, "0,1,2,3,4,") 
Example #23
Source Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def test_wrong_type_should_raise_exception(self):
        with self.assertRaises(AttributeError):
            Template(
                "{% load my_filters %}"
                "{{ d|get_item:'foo' }}"
            ).render(Context({
                'd': list(range(3)),
            })) 
Example #24
Source Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def test_simple_list_value_for_index(self):
        out = Template(
            "{% load my_filters %}"
            "{{ list|get_object:1 }}"
        ).render(Context({
            'list': list(range(3)),
        }))
        self.assertEqual(out, "1") 
Example #25
Source Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def test_basic_value(self):
        out = Template(
            "{% load format_filters %}"
            "{{ f|percentage }}"
        ).render(Context({
            'f': 0.2345678
        }))
        self.assertEqual(out, "23,46 %") 
Example #26
Source Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def test_zero_value(self):
        out = Template(
            "{% load format_filters %}"
            "{{ f|percentage }}"
        ).render(Context({
            'f': 0
        }))
        self.assertEqual(out, "0,00 %") 
Example #27
Source Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def test_no_parameter_raises_exception(self):
        from classytags.exceptions import ArgumentRequiredError
        with self.assertRaises(ArgumentRequiredError):
            out = Template(
                "{% load url_tags %}"
                "{% query %}"
            ).render(Context({})) 
Example #28
Source Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def test_multiple_parameters(self):
        out = Template(
            "{% load url_tags %}"
            "{% query a=1 b=2 %}"
        ).render(Context({}))
        self.assertTrue(out == "a=1&b=2" or out == "b=2&a=1") 
Example #29
Source Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        self.template = Template(
            "{% load currency_filters %}"
            "{{ price|currency }}"
        ) 
Example #30
Source Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def send_emails( request, alert_type ):
    """
    Send all e-mails. 
    """

    alert_emails = AlertEmailTemplate.objects.all().order_by('threshold')
        
    unresolved_alerts = Alert.objects.filter( alerttype__slug=alert_type, resolved=False, hidden=False )
    
    alert_emails = AlertEmailTemplate.objects.filter( hidden=False ).order_by('threshold')
    alert_email_dict = dict( [ (key,[]) for key in alert_emails ] ) 

    for alert in unresolved_alerts:
        number_of_warnings_sent = alert.alertupdate_set.filter( update_type='EMAI' ).count() 
        for email in alert_emails:
            if number_of_warnings_sent < email.threshold:
                alert_email_dict[email].append( alert )
                break

    alert_automations = []
    for email in alert_emails:
        for alert in alert_email_dict[email]:
            email_context = build_context( alert )    
            t = Template( 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) ) 
            # TODO Right here: this should DEFINITELY be a celery task. 
            send_mail( email.subject, rendered_text, "noreply@courses.cs.sfu.ca", [alert.person.email()], fail_silently=True )
            update = AlertUpdate( alert=alert, update_type="EMAI", comments=rendered_text )
            update.save()

    return HttpResponseRedirect(reverse('alerts.views.view_alert_types'))