Python django.template.Context() Examples

The following are 30 code examples of django.template.Context(). 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: OpenMDM   Author: OpenMDM   File: bootstrap.py    License: Apache License 2.0 8 votes vote down vote up
def render(element, markup_classes):
    element_type = element.__class__.__name__.lower()

    if element_type == 'boundfield':
        add_input_classes(element)
        template = get_template("bootstrapform/field.html")
        context = Context({'field': element, 'classes': markup_classes, 'form': element.form})
    else:
        has_management = getattr(element, 'management_form', None)
        if has_management:
            for form in element.forms:
                for field in form.visible_fields():
                    add_input_classes(field)

            template = get_template("bootstrapform/formset.html")
            context = Context({'formset': element, 'classes': markup_classes})
        else:
            for field in element.visible_fields():
                add_input_classes(field)

            template = get_template("bootstrapform/form.html")
            context = Context({'form': element, 'classes': markup_classes})

    return template.render(context) 
Example #2
Source Project: pyconkr-2015   Author: pythonkr   File: helper.py    License: MIT License 6 votes vote down vote up
def send_email_ticket_confirm(request, payment_info):
    """
    :param request Django request object
    :param payment_info Registration object
    """
    mail_title = u"PyCon Korea 2015 등록확인 안내(Registration confirmation)"
    product = Product()
    variables = Context({
        'request': request,
        'payment_info': payment_info,
        'amount': product.price
    })
    html = get_template('mail/ticket_registered_html.html').render(variables)
    text = get_template('mail/ticket_registered_text.html').render(variables)
    
    msg = EmailMultiAlternatives(
        mail_title,
        text,
        settings.EMAIL_SENDER,
        [payment_info.email])
    msg.attach_alternative(html, "text/html")
    msg.send(fail_silently=False) 
Example #3
Source Project: coursys   Author: sfu-fas   File: course_display.py    License: GNU General Public License v3.0 6 votes vote down vote up
def display_form_as_row(form, arg=None):
    """
    Convert the form to a HTML table row
    set arg to be "deleted_flag" to include the deleted field
    """
    output = ["<tr>"]
    if arg == 'hidden':
        output = ['<tr class="hidden">']
    for field in form.visible_fields():
        if field.name == "deleted" and (arg != "deleted_flag"):
            output.append("<td></td>")
            continue
        c = Context({"field":field})
        output.append( FIELD_AS_TD_TEMPLATE.render(c))
    
    for field in form.hidden_fields():
        c = Context({"field":field})
        output.append( FIELD_AS_TD_TEMPLATE_HIDDEN.render(c))
    
    output.append("</tr>")
    
    return mark_safe('\n'.join(output)) 


# from http://stackoverflow.com/questions/35948/django-templates-and-variable-attributes 
Example #4
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 #5
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 #6
Source Project: browserscope   Author: elsigh   File: util.py    License: Apache License 2.0 6 votes vote down vote up
def GetStatsDataTemplatized(params, template='table'):
    """Returns the stats table run through a template.

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

    """
    params['browser_nav'] = result_stats.BROWSER_NAV
    params['is_admin'] = users.is_current_user_admin()
    if not re.search('\?', params['request_path']):
        params['request_path'] = params['request_path'] + '?'
    t = loader.get_template('stats_%s.html' % template)
    template_rendered = t.render(Context(params))
    return template_rendered 
Example #7
Source Project: GTDWeb   Author: lanbing510   File: defaults.py    License: GNU General Public License v2.0 6 votes vote down vote up
def page_not_found(request, template_name='404.html'):
    """
    Default 404 handler.

    Templates: :template:`404.html`
    Context:
        request_path
            The path of the requested URL (e.g., '/app/pages/bad_page/')
    """
    context = {'request_path': request.path}
    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None             # Django will use DEFAULT_CONTENT_TYPE
    except TemplateDoesNotExist:
        template = Engine().from_string(
            '<h1>Not Found</h1>'
            '<p>The requested URL {{ request_path }} was not found on this server.</p>')
        body = template.render(Context(context))
        content_type = 'text/html'
    return http.HttpResponseNotFound(body, content_type=content_type) 
Example #8
Source Project: GTDWeb   Author: lanbing510   File: defaults.py    License: GNU General Public License v2.0 6 votes vote down vote up
def bad_request(request, template_name='400.html'):
    """
    400 error handler.

    Templates: :template:`400.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
    return http.HttpResponseBadRequest(template.render())


# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}. 
Example #9
Source Project: GTDWeb   Author: lanbing510   File: debug.py    License: GNU General Public License v2.0 6 votes vote down vote up
def default_urlconf(request):
    "Create an empty URLconf 404 error response."
    t = DEBUG_ENGINE.from_string(DEFAULT_URLCONF_TEMPLATE)
    c = Context({
        "title": _("Welcome to Django"),
        "heading": _("It worked!"),
        "subheading": _("Congratulations on your first Django-powered page."),
        "instructions": _("Of course, you haven't actually done any work yet. "
            "Next, start your first app by running <code>python manage.py startapp [app_label]</code>."),
        "explanation": _("You're seeing this message because you have <code>DEBUG = True</code> in your "
            "Django settings file and you haven't configured any URLs. Get to work!"),
    })

    return HttpResponse(t.render(c), content_type='text/html')

#
# Templates are embedded in the file so that we know the error handler will
# always work even if the template loader is broken.
# 
Example #10
def search(request):
    query = request.GET['q']
    t = loader.get_template('result.html')
    results = Entry.objects.filter(Q(title__icontains=query) | Q(body__icontains=query))#.order_by('created')
    paginator = Paginator(results, 2) #show 10 articles per page
    page = request.GET.get('page')
    try:
        results = paginator.page(page)
    except PageNotAnInteger:
        results = paginator.page(1)
    except EmptyPage:
        results = paginator.page(paginator.num_pages)

    c = Context({ 'query': query, 'results':results })
    return HttpResponse(t.render(c))

#result.html 
Example #11
Source Project: bioforum   Author: reBiocoder   File: defaults.py    License: MIT License 6 votes vote down vote up
def bad_request(request, exception, template_name=ERROR_400_TEMPLATE_NAME):
    """
    400 error handler.

    Templates: :template:`400.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_400_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
    # No exception content is passed to the template, to not disclose any sensitive information.
    return HttpResponseBadRequest(template.render())


# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}. 
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: 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 #14
Source Project: Servo   Author: fpsw   File: note.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __render__(self, tpl, ctx):
        from django import template
        tpl = template.Template(tpl)
        return tpl.render(template.Context(ctx)) 
Example #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
Source Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def test_simple_dict_value_for_key(self):
        out = Template(
            "{% load my_filters %}"
            "{{ d|get_item:'foo' }}"
        ).render(Context({
            'd': dict(foo="bar"),
        }))
        self.assertEqual(out, "bar") 
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_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 #23
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 #24
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 #25
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 #26
Source Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def test_url_encode_spaces(self):
        out = Template(
            "{% load url_tags %}"
            "{% query q='I got some spaces' %}"
        ).render(Context({}))
        self.assertEqual(out, "q=I+got+some+spaces") 
Example #27
Source Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def test_renders_price_correctly(self):
        out = self.template.render(Context({
            'price': D('10.23'),
        }))
        # remove spaces (from comparision sake)
        out = out.replace("\xa0", '').replace(' ', '')
        self.assertEqual(out, '10,23€') 
Example #28
Source Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def test_handles_string_price_gracefully(self):
        self.template.render(Context({
            'price': ''
        })) 
Example #29
Source Project: pyconkr-2015   Author: pythonkr   File: helper.py    License: MIT License 5 votes vote down vote up
def sendEmailToken(request, token):
    variables = Context({
        'request': request,
        'token': token,
    })
    html = get_template('mail/token_html.html').render(variables)
    text = get_template('mail/token_text.html').render(variables)

    msg = EmailMultiAlternatives(
        settings.EMAIL_LOGIN_TITLE,
        text,
        settings.EMAIL_SENDER,
        [token.email])
    msg.attach_alternative(html, "text/html")
    msg.send(fail_silently=False) 
Example #30
Source Project: coursys   Author: sfu-fas   File: course_display.py    License: GNU General Public License v3.0 5 votes vote down vote up
def error_note(form):
    """
    Display the pre-form note about errors (if any).
    """
    output = ""
    if form.errors:
        c = Context({})
        output = ERROR_NOTE_TEMPLATE.render(c)

    return mark_safe(output)