當前位置: 首頁>>代碼示例>>Python>>正文


Python template.Context方法代碼示例

本文整理匯總了Python中django.template.Context方法的典型用法代碼示例。如果您正苦於以下問題:Python template.Context方法的具體用法?Python template.Context怎麽用?Python template.Context使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.template的用法示例。


在下文中一共展示了template.Context方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: render

# 需要導入模塊: from django import template [as 別名]
# 或者: from django.template import Context [as 別名]
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) 
開發者ID:OpenMDM,項目名稱:OpenMDM,代碼行數:26,代碼來源:bootstrap.py

示例2: send_email_ticket_confirm

# 需要導入模塊: from django import template [as 別名]
# 或者: from django.template import Context [as 別名]
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) 
開發者ID:pythonkr,項目名稱:pyconkr-2015,代碼行數:24,代碼來源:helper.py

示例3: display_form_as_row

# 需要導入模塊: from django import template [as 別名]
# 或者: from django.template import Context [as 別名]
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 
開發者ID:sfu-fas,項目名稱:coursys,代碼行數:27,代碼來源:course_display.py

示例4: view_email_preview

# 需要導入模塊: from django import template [as 別名]
# 或者: from django.template import Context [as 別名]
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 }) 
開發者ID:sfu-fas,項目名稱:coursys,代碼行數:20,代碼來源:views.py

示例5: get

# 需要導入模塊: from django import template [as 別名]
# 或者: from django.template import Context [as 別名]
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)) 
開發者ID:stormsha,項目名稱:StormOnline,代碼行數:24,代碼來源:editable.py

示例6: GetStatsDataTemplatized

# 需要導入模塊: from django import template [as 別名]
# 或者: from django.template import Context [as 別名]
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 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:26,代碼來源:util.py

示例7: page_not_found

# 需要導入模塊: from django import template [as 別名]
# 或者: from django.template import Context [as 別名]
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) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:23,代碼來源:defaults.py

示例8: bad_request

# 需要導入模塊: from django import template [as 別名]
# 或者: from django.template import Context [as 別名]
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 %}. 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:19,代碼來源:defaults.py

示例9: default_urlconf

# 需要導入模塊: from django import template [as 別名]
# 或者: from django.template import Context [as 別名]
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.
# 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:21,代碼來源:debug.py

示例10: search

# 需要導入模塊: from django import template [as 別名]
# 或者: from django.template import Context [as 別名]
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 
開發者ID:agusmakmun,項目名稱:Some-Examples-of-Simple-Python-Script,代碼行數:19,代碼來源:multiple search, query and page url.py

示例11: bad_request

# 需要導入模塊: from django import template [as 別名]
# 或者: from django.template import Context [as 別名]
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 %}. 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:23,代碼來源:defaults.py

示例12: templates

# 需要導入模塊: from django import template [as 別名]
# 或者: from django.template import Context [as 別名]
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}) 
開發者ID:fpsw,項目名稱:Servo,代碼行數:15,代碼來源:note.py

示例13: render

# 需要導入模塊: from django import template [as 別名]
# 或者: from django.template import Context [as 別名]
def render(self, context):
        from django import template
        tpl = template.Template(self.content)
        return tpl.render(template.Context({'order': context})) 
開發者ID:fpsw,項目名稱:Servo,代碼行數:6,代碼來源:common.py

示例14: __render__

# 需要導入模塊: from django import template [as 別名]
# 或者: from django.template import Context [as 別名]
def __render__(self, tpl, ctx):
        from django import template
        tpl = template.Template(tpl)
        return tpl.render(template.Context(ctx)) 
開發者ID:fpsw,項目名稱:Servo,代碼行數:6,代碼來源:note.py

示例15: render_template

# 需要導入模塊: from django import template [as 別名]
# 或者: from django.template import Context [as 別名]
def render_template(self, template_path, context):
        template_str = self.resource_string(template_path)
        template = Template(template_str)
        return template.render(Context(context)) 
開發者ID:raccoongang,項目名稱:edx_xblock_scorm,代碼行數:6,代碼來源:scormxblock.py


注:本文中的django.template.Context方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。