本文整理匯總了Python中django.template.loader.get_template方法的典型用法代碼示例。如果您正苦於以下問題:Python loader.get_template方法的具體用法?Python loader.get_template怎麽用?Python loader.get_template使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.template.loader
的用法示例。
在下文中一共展示了loader.get_template方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: render
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import get_template [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: hijack_field
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import get_template [as 別名]
def hijack_field(self, obj):
hijack_attributes = hijack_settings.HIJACK_URL_ALLOWED_ATTRIBUTES
if 'user_id' in hijack_attributes:
hijack_url = reverse('hijack:login_with_id', args=(obj.pk, ))
elif 'email' in hijack_attributes:
hijack_url = reverse('hijack:login_with_email', args=(obj.email, ))
else:
hijack_url = reverse('hijack:login_with_username', args=(obj.username, ))
button_template = get_template(hijack_admin_settings.HIJACK_BUTTON_TEMPLATE)
button_context = {
'hijack_url': hijack_url,
'username': str(obj),
}
return button_template.render(button_context)
示例3: send_email_ticket_confirm
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import get_template [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)
示例4: render
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import get_template [as 別名]
def render(self, context):
request = context["request"]
post = getattr(request, "POST", None)
form = template.Variable(self.value).resolve(context)
t = get_template("forms/includes/built_form.html")
context["form"] = form
form_args = (form, context, post or None)
form_for_form = FormForForm(*form_args)
# kind of a hack
# add the 'data-verify' attribute if the field is marked
# as a verifiable field
for i, field in enumerate(form_for_form.form_fields):
if field.verify:
form_for_form.fields[field.slug].widget.attrs['data-verify'] = True
# We give to all the form fields a common class so we can reference
# them in the frontend
fieldAttrs = form_for_form.fields[field.slug].widget.attrs
fieldAttrs['class'] = fieldAttrs['class'] + ' form-field'
context["form_for_form"] = form_for_form
return t.render(context)
示例5: email_user
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import get_template [as 別名]
def email_user(self, text_template, html_template, context):
offering = context['offering']
headers = {
'Precedence': 'bulk',
'Auto-Submitted': 'auto-generated',
'X-coursys-topic': 'discussion',
'X-course': offering.slug,
'Sender': settings.DEFAULT_SENDER_EMAIL,
}
to_email = context['to'].email()
if offering.taemail():
from_email = "%s <%s>" % (offering.name(), offering.taemail())
else:
from_email = settings.DEFAULT_SENDER_EMAIL
text_content = get_template(text_template).render(context)
html_content = get_template(html_template).render(context)
msg = EmailMultiAlternatives(context['subject'], text_content, from_email, [to_email], headers=headers)
msg.attach_alternative(html_content, "text/html")
msg.send()
示例6: email_notify_completed
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import get_template [as 別名]
def email_notify_completed(self, request, admin, email_cc=None):
plaintext = get_template('onlineforms/emails/notify_completed.txt')
html = get_template('onlineforms/emails/notify_completed.html')
email_context = {'formsub': self, 'admin': admin}
subject = '%s for %s submission complete' % (self.form.title, self.initiator.name())
from_email = FormFiller.form_full_email(admin)
to = self.initiator.full_email()
if email_cc:
email_cc = [l.strip() for l in email_cc.split(',')]
msg = EmailMultiAlternatives(subject=subject, body=plaintext.render(email_context),
from_email=from_email, to=[to], bcc=[admin.full_email()], cc=email_cc,
headers={'X-coursys-topic': 'onlineforms'})
msg.attach_alternative(html.render(email_context), "text/html")
msg.send()
FormLogEntry.create(form_submission=self, category='MAIL',
description='Notified %s that form submission was completed by %s.'
% (to, from_email))
示例7: email_notify_new_owner
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import get_template [as 別名]
def email_notify_new_owner(self, request, admin):
plaintext = get_template('onlineforms/emails/notify_new_owner.txt')
html = get_template('onlineforms/emails/notify_new_owner.html')
full_url = request.build_absolute_uri(reverse('onlineforms:view_submission',
kwargs={'form_slug': self.form.slug,
'formsubmit_slug': self.slug}))
email_context = {'formsub': self, 'admin': admin, 'adminurl': full_url}
subject = '%s submission transferred' % (self.form.title)
from_email = FormFiller.form_full_email(admin)
to = self.owner.notify_emails()
msg = EmailMultiAlternatives(subject=subject, body=plaintext.render(email_context),
from_email=from_email, to=to, bcc=[admin.full_email()],
headers={'X-coursys-topic': 'onlineforms'})
msg.attach_alternative(html.render(email_context), "text/html")
msg.send()
FormLogEntry.create(form_submission=self, category='MAIL',
description='Notified group "%s" that form submission was transferred to them.'
% (self.owner.name,))
示例8: GetStatsDataTemplatized
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import get_template [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
示例9: serve_pdf
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import get_template [as 別名]
def serve_pdf(self, request):
# Render html content through html template with context
template = get_template(settings.PDF_TEMPLATE)
context = {
'invoice': self,
}
html = template.render(context)
# Write PDF to file
document_html = HTML(string=html, base_url=request.build_absolute_uri())
document = document_html.render()
if len(document.pages) > 1:
for page in document.pages[1:]:
str(page)
pdf = document.write_pdf()
else:
pdf = document.write_pdf()
#response = HttpResponse(html)
response = HttpResponse(pdf, content_type='application/pdf')
response['Content-Disposition'] = 'filename="Invoice {0} | Invoice {0}.pdf"'.format(self.id)
return response
示例10: page_not_found
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import get_template [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)
示例11: bad_request
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import get_template [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 %}.
示例12: render_flatpage
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import get_template [as 別名]
def render_flatpage(request, f):
"""
Internal interface to the flat page view.
"""
# If registration is required for accessing this page, and the user isn't
# logged in, redirect to the login page.
if f.registration_required and not request.user.is_authenticated():
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(request.path)
if f.template_name:
template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
else:
template = loader.get_template(DEFAULT_TEMPLATE)
# To avoid having to always use the "|safe" filter in flatpage templates,
# mark the title and content as already safe (since they are raw HTML
# content in the first place).
f.title = mark_safe(f.title)
f.content = mark_safe(f.content)
response = HttpResponse(template.render({'flatpage': f}, request))
return response
示例13: search
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import get_template [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
示例14: post
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import get_template [as 別名]
def post(self, request):
str_xml = ET.fromstring(request.body)
from_user = str_xml.find('FromUserName').text
to_user = str_xml.find('ToUserName').text
cur_time = str(int(time.time()))
msg_type = str_xml.find('MsgType').text
content = '...'
if msg_type == 'text':
content = str_xml.find('Content').text
if '[Unsupported Message]' in content:
res = 'Error: unknow message'
else:
res = core.chat.Chat(db).response(from_user, content)
else:
res = "Sorry, I can't chat by %s" % msg_type
template = loader.get_template('wechat/text_message_template.xml')
context = {'toUser': from_user,
'fromUser': to_user,
'currentTtime': cur_time,
'content': res}
context_xml = template.render(context)
log_str = '\nUser: %s\nAsk: %s\nAnswer: %s\n' % \
(from_user, content, res)
core.common.ChatLog().write(log_str)
return HttpResponse(context_xml)
示例15: do_loadmacros
# 需要導入模塊: from django.template import loader [as 別名]
# 或者: from django.template.loader import get_template [as 別名]
def do_loadmacros(parser, token):
try:
tag_name, filename = token.split_contents()
except IndexError:
m = ("'%s' tag requires at least one argument (macro name)"
% token.contents.split()[0])
raise template.TemplateSyntaxError(m)
if filename[0] in ('"', "'") and filename[-1] == filename[0]:
filename = filename[1:-1]
t = get_template(filename)
macros = t.nodelist.get_nodes_by_type(DefineMacroNode)
## Metadata of each macro are stored in a new attribute
## of 'parser' class. That way we can access it later
## in the template when processing 'usemacro' tags.
_setup_macros_dict(parser)
for macro in macros:
parser._macros[macro.name] = macro
return LoadMacrosNode()