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 File: bootstrap.py    From OpenMDM with 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 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 #3
Source File: debug.py    From GTDWeb with 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 #4
Source File: helper.py    From pyconkr-2015 with 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 #5
Source File: multiple search, query and page url.py    From Some-Examples-of-Simple-Python-Script with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #6
Source File: course_display.py    From coursys with 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 #7
Source File: defaults.py    From GTDWeb with 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 #8
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 #9
Source File: util.py    From browserscope with 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 #10
Source File: defaults.py    From GTDWeb with 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 #11
Source File: defaults.py    From bioforum with 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 File: defaults.py    From bioforum with MIT License 5 votes vote down vote up
def server_error(request, template_name=ERROR_500_TEMPLATE_NAME):
    """
    500 error handler.

    Templates: :template:`500.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_500_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
    return HttpResponseServerError(template.render()) 
Example #13
Source File: i18n.py    From bioforum with MIT License 5 votes vote down vote up
def render_javascript_catalog(catalog=None, plural=None):
    template = Engine().from_string(js_catalog_template)

    def indent(s):
        return s.replace('\n', '\n  ')

    context = Context({
        'catalog_str': indent(json.dumps(
            catalog, sort_keys=True, indent=2)) if catalog else None,
        'formats_str': indent(json.dumps(
            get_formats(), sort_keys=True, indent=2)),
        'plural': plural,
    })

    return HttpResponse(template.render(context), 'text/javascript') 
Example #14
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 #15
Source File: package_title_style.py    From DCRM with GNU Affero General Public License v3.0 5 votes vote down vote up
def package_title_style(context):
    ctx = Context(context)
    if 'c_package__exact' in context.request.GET:
        ctx.update({
            "filtered_by_package": context.request.GET['c_package__exact']
        })
    return ctx 
Example #16
Source File: package_title_script.py    From DCRM with GNU Affero General Public License v3.0 5 votes vote down vote up
def package_title_script(context):
    ctx = Context(context)
    if 'c_package__exact' in context.request.GET:
        ctx.update({
            "filtered_by_package": context.request.GET['c_package__exact']
        })
    return ctx 
Example #17
Source File: defaults.py    From bioforum with MIT License 5 votes vote down vote up
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME):
    """
    Default 404 handler.

    Templates: :template:`404.html`
    Context:
        request_path
            The path of the requested URL (e.g., '/app/pages/bad_page/')
        exception
            The message from the exception which triggered the 404 (if one was
            supplied), or the exception class name
    """
    exception_repr = exception.__class__.__name__
    # Try to get an "interesting" exception message, if any (and not the ugly
    # Resolver404 dictionary)
    try:
        message = exception.args[0]
    except (AttributeError, IndexError):
        pass
    else:
        if isinstance(message, str):
            exception_repr = message
    context = {
        'request_path': request.path,
        'exception': exception_repr,
    }
    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None             # Django will use DEFAULT_CONTENT_TYPE
    except TemplateDoesNotExist:
        if template_name != ERROR_404_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        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 HttpResponseNotFound(body, content_type=content_type) 
Example #18
Source File: note.py    From Servo with 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 #19
Source File: debug.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_traceback_text(self):
        "Return plain text version of debug 500 HTTP error page."
        t = DEBUG_ENGINE.from_string(TECHNICAL_500_TEXT_TEMPLATE)
        c = Context(self.get_traceback_data(), autoescape=False, use_l10n=False)
        return t.render(c) 
Example #20
Source File: debug.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_traceback_html(self):
        "Return HTML version of debug 500 HTTP error page."
        t = DEBUG_ENGINE.from_string(TECHNICAL_500_TEMPLATE)
        c = Context(self.get_traceback_data(), use_l10n=False)
        return t.render(c) 
Example #21
Source File: csrf.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def csrf_failure(request, reason=""):
    """
    Default view used when request fails CSRF protection
    """
    from django.middleware.csrf import REASON_NO_REFERER, REASON_NO_CSRF_COOKIE
    t = Engine().from_string(CSRF_FAILURE_TEMPLATE)
    c = Context({
        'title': _("Forbidden"),
        'main': _("CSRF verification failed. Request aborted."),
        'reason': reason,
        'no_referer': reason == REASON_NO_REFERER,
        'no_referer1': _(
            "You are seeing this message because this HTTPS site requires a "
            "'Referer header' to be sent by your Web browser, but none was "
            "sent. This header is required for security reasons, to ensure "
            "that your browser is not being hijacked by third parties."),
        'no_referer2': _(
            "If you have configured your browser to disable 'Referer' headers, "
            "please re-enable them, at least for this site, or for HTTPS "
            "connections, or for 'same-origin' requests."),
        'no_cookie': reason == REASON_NO_CSRF_COOKIE,
        'no_cookie1': _(
            "You are seeing this message because this site requires a CSRF "
            "cookie when submitting forms. This cookie is required for "
            "security reasons, to ensure that your browser is not being "
            "hijacked by third parties."),
        'no_cookie2': _(
            "If you have configured your browser to disable cookies, please "
            "re-enable them, at least for this site, or for 'same-origin' "
            "requests."),
        'DEBUG': settings.DEBUG,
        'docs_version': get_docs_version(),
        'more': _("More information is available with DEBUG=True."),
    })
    return HttpResponseForbidden(t.render(c), content_type='text/html') 
Example #22
Source File: defaults.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def permission_denied(request, template_name='403.html'):
    """
    Permission denied (403) handler.

    Templates: :template:`403.html`
    Context: None

    If the template does not exist, an Http403 response containing the text
    "403 Forbidden" (as per RFC 2616) will be returned.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
    return http.HttpResponseForbidden(template.render(request=request)) 
Example #23
Source File: defaults.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def server_error(request, template_name='500.html'):
    """
    500 error handler.

    Templates: :template:`500.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
    return http.HttpResponseServerError(template.render()) 
Example #24
Source File: i18n.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def render_javascript_catalog(catalog=None, plural=None):
    template = Engine().from_string(js_catalog_template)
    indent = lambda s: s.replace('\n', '\n  ')
    context = Context({
        'catalog_str': indent(json.dumps(
            catalog, sort_keys=True, indent=2)) if catalog else None,
        'formats_str': indent(json.dumps(
            get_formats(), sort_keys=True, indent=2)),
        'plural': plural,
    })

    return http.HttpResponse(template.render(context), 'text/javascript') 
Example #25
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 #26
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 #27
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) 
Example #28
Source File: test_tags.py    From django-active-link with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_match_url_with_kwargs_with_multiple(self):
        template = Template("""
            {% load active_link_tags %}
            {% active_link 'simple || detailed-action' pk=12 %}
        """)
        context = Context({'request': self.client.get('/detailed/action/12/')})
        html = template.render(context)
        assert 'active' in html 
Example #29
Source File: test_tags.py    From django-active-link with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_settings_strict(self):
        template = Template("""
            {% load active_link_tags %}
            {% active_link 'simple-action' %}
        """)
        context = Context({'request': self.client.get('/simple/')})
        html = template.render(context)
        assert 'active' not in html 
Example #30
Source File: test_tags.py    From django-active-link with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_settings_css_class(self):
        template = Template("""
            {% load active_link_tags %}
            {% active_link 'simple' %}
        """)
        context = Context({'request': self.client.get('/simple/')})
        html = template.render(context)
        assert 'my-active-class' in html