本文整理汇总了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)
示例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)
示例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
示例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 })
示例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))
示例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
示例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)
示例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 %}.
示例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.
#
示例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 %}.
示例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})
示例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}))
示例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))
示例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))