def gallery_detail(request, gallery_slug, is_xml=False, is_flash=False): """ Gallery detail page Templates: `media/gallery_detail` Context: gallery: `media.galleries` object photo_list: list of `media.galleryphotos` in the gallery """ try: gal = Gallery.on_site.get(slug__exact=gallery_slug) except Gallery.DoesNotExist: raise Http404 if is_xml: t = loader.select_template(["media/gallery_xml_%s_detail.html" % gal.template_prefix, "media/gallery_xml_detail.html"]) elif is_flash: t = loader.select_template(["media/gallery_flash_%s_detail.html" % gal.template_prefix, "media/gallery_flash_detail.html"]) else: t = loader.select_template(["media/gallery_%s_detail.html" % gal.template_prefix, "media/gallery_detail.html"]) c = Context(request, { 'gallery': gal, 'photo_list': gal.galleryphoto_set.all(), }) response = HttpResponse(t.render(c)) populate_xheaders(request, response, 'media', Gallery, gal.id) return response
def get_templates(self, action): """ Return a subject, text, HTML tuple with e-mail templates for a particular action. Returns a tuple with subject, text and e-mail template. """ assert action in ACTIONS + ("message",), "Unknown action: %s" % action # Common substitutions for filenames tpl_subst = {"action": action, "newsletter": self.slug} # Common root path for all the templates tpl_root = "newsletter/message/" subject_template = select_template( [ tpl_root + "%(newsletter)s/%(action)s_subject.txt" % tpl_subst, tpl_root + "%(action)s_subject.txt" % tpl_subst, ] ) text_template = select_template( [tpl_root + "%(newsletter)s/%(action)s.txt" % tpl_subst, tpl_root + "%(action)s.txt" % tpl_subst] ) if self.send_html: html_template = select_template( [tpl_root + "%(newsletter)s/%(action)s.html" % tpl_subst, tpl_root + "%(action)s.html" % tpl_subst] ) else: # HTML templates are not required html_template = None return (subject_template, text_template, html_template)
def gallery_set_detail(request, slug, is_xml=None, is_flash=None): try: set = GallerySet.on_site.get(slug=slug) except GallerySet.DoesNotExist: raise Http404 pag = paginator.ObjectPaginator(set.gallery_set.all(), 20) try: page_number = int(request.GET.get('page', 1)) - 1 except ValueError: page_number = 0 try: gallery_list = pag.get_page(page_number) except paginator.InvalidPage: raise Http404 if is_xml: t = loader.select_template(["%s_xml" % set.template_name, 'media/galleryset_xml_detail.html']) elif is_flash: t = loader.select_template(["%s_flash" % set.template_name, 'media/galleryset_flash_detail.html']) else: t = loader.select_template([set.template_name, 'media/galleryset_detail.html']) c = Context(request, { 'object': set, 'gallery_list': gallery_list, 'has_next_page': pag.has_next_page(page_number), 'has_previous_page': pag.has_previous_page(page_number), 'pages': pag.pages, 'next_page': page_number + 2, 'previous_page': page_number, }) response = HttpResponse(t.render(c)) populate_xheaders(request, response, 'media', GallerySet, set.id) return response
def delete_account(request): context = {} if request.method == 'POST': confirma = request.POST.get('borrar', False) if confirma: try: token = str(uuid4()) user = request.user cache.set(token, user.username, timeout=settings.USER_DELETION_TTL) emails = ['registration/default/delete_email_subject.txt', 'registration/default/delete_email_subject.txt'] subject = render_to_string(select_template(emails).name, {'site': settings.SITE_URL}) delete_url = 'accounts:registration-confirm-deletion' mail_vars = {'site': settings.SITE_URL, 'path': reverse(delete_url, args=[token])} emails = ['registration/default/delete_email.html', 'registration/default/delete_email.html'] html_content = render_to_string(select_template(emails).name, mail_vars) msg = EmailMessage(subject.strip("\n"), html_content, settings.DEFAULT_FROM_EMAIL, [user.email]) # Main content is now text/html msg.content_subtype = "html" msg.send() mensaje = _(u'Te enviamos instrucciones para completar el cierre de tu cuenta.') messages.success(request, mensaje) auth_logout(request) except Exception as e: logger.error("Obtained error {e}".format(e=e.message)) return render(request, 'accounts/delete_account_success.html', context) return render(request, 'accounts/delete_account.html', context)
def get_templates(self, action, lang='pl'): """ Return a subject, text, HTML tuple with e-mail templates for a particular action. Returns a tuple with subject, text and e-mail template. """ # Common substitutions for filenames template_subst = { 'action': action, 'newsletter': self.slug } assert action in [ 'subscribe', 'unsubscribe', 'update', 'message' ], 'Unknown action %s' % action # Common root path for all the templates template_root = 'newsletter/message/' # activate current translation for the message translation.activate(lang) subject_template = select_template([ template_root + '%(newsletter)s/%(action)s_subject.txt' % template_subst, template_root + '%(action)s_subject.txt' % template_subst, ]) text_template = select_template([ template_root + '%(newsletter)s/%(action)s.txt' % template_subst, template_root + '%(action)s.txt' % template_subst, ]) html_template = self.get_html_template() return (subject_template, text_template, html_template)
def send_confirmation(self, obj, email_address, additional_context=None, subject_template_path=None, body_template_path=None): confirmation_key = generate_key() current_site = Site.objects.get_current() activate_url = generate_activation_url(confirmation_key) context = Context({ 'activate_url': activate_url, 'current_site': current_site, 'confirmation_key': confirmation_key, 'target': obj, 'days': getattr(settings, 'EMAIL_CONFIRMATION_DAYS', 10), }) if additional_context is not None: context.update(additional_context) templates = [ 'confirmation/%s_confirmation_email_subject.txt' % obj._meta.model_name, 'confirmation/confirmation_email_subject.txt', ] if subject_template_path: template = loader.get_template(subject_template_path) else: template = loader.select_template(templates) subject = template.render(context).strip().replace(u'\n', u' ') # no newlines, please templates = [ 'confirmation/%s_confirmation_email_body.txt' % obj._meta.model_name, 'confirmation/confirmation_email_body.txt', ] if body_template_path: template = loader.get_template(body_template_path) else: template = loader.select_template(templates) body = template.render(context) send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [email_address]) return self.create(content_object=obj, date_sent=now(), confirmation_key=confirmation_key)
def get_response(self, request, context={}, template=None, denominator=None, extend_template=None, template_select=None): if extend_template is None: extend_templates = [getattr(self, "base_template", "base")] else: extend_templates = [extend_template] if (request.is_ajax() or (settings.DEBUG and "_lyra_ajax" in request.GET)): extend_templates.insert(0, "ajax_base") if template and template_select is None: template_select = [template] elif template_select is None: raise ValueError("provide one of template or " "template_select, not both or neither") tpl = loader.select_template( self.get_template_names(template_select, denominator)) base_context = dict( self.extra_context, **{ "base": loader.select_template( self.get_template_names(extend_templates, denominator))} ) context = dict(base_context, **context) ctx = template_module.RequestContext(request, context) ctx.current_app = self.app_namespace return http.HttpResponse(tpl.render(ctx))
def notify_new_reply_by_email(reply): helprequest = reply.helprequest recipient = None if reply.author != helprequest.requester: recipient = helprequest.requester elif helprequest.bikeanjo: recipient = helprequest.bikeanjo if not recipient: return site = Site.objects.filter(id=settings.SITE_ID).first() subject = u'Você recebeu uma nova mensagem de %s!' % reply.author.get_full_name() from_email = settings.DEFAULT_FROM_EMAIL data = { 'helprequest': helprequest, 'recipient': recipient, 'sender': reply.author, 'site': site, } with translation.override(set_language(recipient)): template_name = 'emails/new_msg_to_%s.html' % recipient.role html = select_template([template_name]).render(data) template_name = 'emails/new_msg_to_%s.txt' % recipient.role text = select_template([template_name]).render(data) msg = EmailMultiAlternatives(subject, text, from_email, [recipient.email]) msg.attach_alternative(html, "text/html") msg.send()
def page(request, page_name): page = get_object_or_404(Page, name=page_name) if not page.active and not request.user.is_staff: return HttpResponseRedirect(reverse(settings.PERMISSION_DENIED_URL)) if page.restricted: if request.user.is_anonymous(): return HttpResponseRedirect( reverse('website:restricted_page_not_logged_in') ) elif not request.user.is_staff and not \ request.user.has_perm('website.can_view_restricted'): return HttpResponseRedirect(reverse(settings.PERMISSION_DENIED_URL)) template = TEMPLATES['no-img'] if page.pictures.count() > 0: template = TEMPLATES[page.layout] try: select_template( ['website/{}_extra.html'.format(page_name)] ) include_html = 'website/{}_extra.html'.format(page_name) except TemplateDoesNotExist: include_html = '' return TemplateResponse( request, template, {'page': page, 'include_html': include_html} )
def get_templates(self, action): """ Return a subject, text, HTML tuple with e-mail templates for a particular action. Returns a tuple with subject, text and e-mail template. """ assert action in ACTIONS + ('message', ), 'Unknown action: %s' % action # Common substitutions for filenames tpl_subst = { 'action': action, 'newsletter': self.slug } # Common root path for all the templates tpl_root = 'newsletter/message/' text_template = select_template([ tpl_root + '%(newsletter)s/%(action)s.txt' % tpl_subst, tpl_root + '%(action)s.txt' % tpl_subst, ]) if self.send_html: html_template = select_template([ tpl_root + '%(newsletter)s/%(action)s.html' % tpl_subst, tpl_root + '%(action)s.html' % tpl_subst, ]) else: # HTML templates are not required html_template = None return (text_template, html_template)
def send_registration_approval(self): template_txt = select_template([ 'leprikon/registration-approved-mail/{}.txt'.format(self.subject.subject_type.slug), 'leprikon/registration-approved-mail/{}.txt'.format(self.subject.subject_type.subject_type), 'leprikon/registration-approved-mail/subject.txt', ]) template_html = select_template([ 'leprikon/registration-approved-mail/{}.html'.format(self.subject.subject_type.slug), 'leprikon/registration-approved-mail/{}.html'.format(self.subject.subject_type.subject_type), 'leprikon/registration-approved-mail/subject.html', ]) site = LeprikonSite.objects.get_current() context = { 'object': self, 'site': site, } content_txt = template_txt.render(context) content_html = template_html.render(context) msg = EmailMultiAlternatives( subject = self.registration_approval_subject, body = content_txt, from_email = settings.SERVER_EMAIL, to = self.all_recipients, headers = {'X-Mailer': 'Leprikon (http://leprikon.cz/)'}, ) msg.attach_alternative(content_html, 'text/html') msg.send()
def save(self): subject_template = select_template([ '{}/email/password-reset-subject.txt'.format(app_settings.APP_LABEL), 'shop/email/password-reset-subject.txt', ]) body_text_template = select_template([ '{}/email/password-reset-body.txt'.format(app_settings.APP_LABEL), 'shop/email/password-reset-body.txt', ]) body_html_template = select_template([ '{}/email/password-reset-body.html'.format(app_settings.APP_LABEL), 'shop/email/password-reset-body.html', ]) try: page = Page.objects.select_related('node').get(reverse_id='password-reset-confirm', publisher_is_draft=False) except Page.DoesNotExist: try: password_reset_confirm_url = reverse('password-reset-confirm') except NoReverseMatch: password_reset_confirm_url = self.invalid_password_reset_confirm_url else: language = get_language_from_request(self.context['request']) password_reset_confirm_url = page.get_absolute_url(language) opts = { 'use_https': self.context['request'].is_secure(), 'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'), 'request': self.context['request'], 'subject_template_name': subject_template.template.name, 'email_template_name': body_text_template.template.name, 'html_email_template_name': body_html_template.template.name, 'extra_email_context': {'password_reset_confirm_url': password_reset_confirm_url} } self.reset_form.save(**opts)
def send_payment_request(self): template_txt = select_template([ 'leprikon/payment-request-mail/{}.txt'.format(self.subject.subject_type.slug), 'leprikon/payment-request-mail/{}.txt'.format(self.subject.subject_type.subject_type), 'leprikon/payment-request-mail/subject.txt', ]) template_html = select_template([ 'leprikon/payment-request-mail/{}.html'.format(self.subject.subject_type.slug), 'leprikon/payment-request-mail/{}.html'.format(self.subject.subject_type.subject_type), 'leprikon/payment-request-mail/subject.html', ]) site = LeprikonSite.objects.get_current() context = { 'object': self, 'site': site, } content_txt = template_txt.render(context) content_html = template_html.render(context) msg = EmailMultiAlternatives( subject = self.payment_request_subject, body = content_txt, from_email = settings.SERVER_EMAIL, to = self.all_recipients, headers = {'X-Mailer': 'Leprikon (http://leprikon.cz/)'}, ) msg.attach_alternative(content_html, 'text/html') if site.bank_account: qr_code = MIMEImage(self.get_qr_code()) qr_code.add_header('Content-ID', '<qr_code>') msg.attach(qr_code) msg.send()
def send_mail(self): template_txt = select_template([ 'leprikon/{}-mail/{}.txt'.format(self.pdf_export, self.subject.subject_type.slug), 'leprikon/{}-mail/{}.txt'.format(self.pdf_export, self.subject.subject_type.subject_type), 'leprikon/{}-mail/subject.txt'.format(self.pdf_export), ]) template_html = select_template([ 'leprikon/{}-mail/{}.html'.format(self.pdf_export, self.subject.subject_type.slug), 'leprikon/{}-mail/{}.html'.format(self.pdf_export, self.subject.subject_type.subject_type), 'leprikon/{}-mail/subject.html'.format(self.pdf_export), ]) context = { 'object': self, 'site': LeprikonSite.objects.get_current(), } content_txt = template_txt.render(context) content_html = template_html.render(context) msg = EmailMultiAlternatives( subject = self.mail_subject, body = content_txt, from_email = settings.SERVER_EMAIL, to = self.all_recipients, headers = {'X-Mailer': 'Leprikon (http://leprikon.cz/)'}, ) msg.attach_alternative(content_html, 'text/html') msg.attach(self.pdf_filename, self.get_pdf(), 'application/pdf') for attachment in self.all_attachments: msg.attach_file(attachment.file.file.path) msg.send()
def _send_password(self, request, user, password): current_site = get_current_site(request) context = { 'site_name': current_site.name, 'absolute_base_uri': request.build_absolute_uri('/'), 'email': user.email, 'password': password, 'user': user, } subject_template = select_template([ '{}/email/register-user-subject.txt'.format(app_settings.APP_LABEL), 'shop/email/register-user-subject.txt', ]) # Email subject *must not* contain newlines subject = ''.join(subject_template.render(context).splitlines()) body_text_template = select_template([ '{}/email/register-user-body.txt'.format(app_settings.APP_LABEL), 'shop/email/register-user-body.txt', ]) body_html_template = select_template([ '{}/email/register-user-body.html'.format(app_settings.APP_LABEL), 'shop/email/register-user-body.html', ], using='post_office') message = body_text_template.render(context) html_message = body_html_template.render(context) from_email = getattr(settings, 'DEFAULT_FROM_EMAIL') user.email_user(subject, message, from_email=from_email, html_message=html_message) email_queued()
def base_templates(request): ''' To be used as a context_processor so as to provide a fallback if the hosting project does not have either base.html or base_site.html templates ''' _docengine_registration = getattr(settings, 'DOCENGINE_REGISTRATION', False) _registration_open = getattr(settings, 'REGISTRATION_OPEN', True) _USER_PROFILE = getattr(settings, 'REGISTER_USER_PROFILE', getattr(settings, 'DOCENGINE_USER_PROFILE', None)) _base_prefix='' if hasattr(request, 'session') and 'subdomain' in request.session: if hasattr(settings, 'DOMAINS_PATHS'): _base_prefix = dict(settings.DOMAINS_PATHS).get(request.session['subdomain'], '') else: _base_prefix = request.session['subdomain'] + '/' context = { 'client_project': getattr(settings, 'CLIENT_PROJECT', 'DocEngine'), 'base_template': loader.select_template([_base_prefix+'base.html', 'base.html', 'common/base.html']), 'base_site_template': loader.select_template([_base_prefix+'base_site.html', 'base_site.html', 'common/base_site.html']), 'REGISTRATION_OPEN': _docengine_registration and _registration_open, 'HAS_PROFILE': isinstance(_USER_PROFILE, basestring), 'PROJECT_TITLE': os.path.split(settings.ENVIRON_DIR)[1] } return context
def get_response(self, request, context={}, template=None, denominator=None, extend_template=None, template_select=None): if extend_template is None: extend_template = getattr(self, "base_template", "base") if template and template_select is None: template_select = [template] elif template_select is None: raise ValueError("provide one of template or " "template_select, not both or neither") tpl = loader.select_template( self.get_template_names(template_select, denominator)) base_context = dict( self.extra_context, **{ "base": loader.select_template( self.get_template_names([extend_template], denominator))} ) context = dict(base_context, **context) ctx = template_module.RequestContext(request, context) ctx.current_app = self.app_namespace return http.HttpResponse(tpl.render(ctx))
def queryset_render_multiple_original(queryset, name, attr_str, data, parent=None): try: t_item=loader.select_template(["select_multiple_widget_items_original.html"]) except TemplateDoesNotExist: t_item=Template(default_select_multiple_template_original[0]) try: t=loader.select_template(["select_multiple_widget_original.html"]) except TemplateDoesNotExist: t=Template(default_select_multiple_template_original[1]) if parent and len(parent)>0 and (type(parent) in (type((1,)), type([1,]))): parent1, parent2=name else: parent1, parent2=parent, None if data==None: data=[]#当新增数据时,执行此语句 roots=queryset_group(queryset, parent1, data) #多对多多选框没有内容可以显示时,显示返回模型中Admin类中定义的报错信息 rootserror='' if roots=={}: model=queryset.model if hasattr(model.Admin,"blankerror_text"): rootserror=model.Admin.blankerror_text return t.render( Context({'roots': dict([(root, t_item.render(Context({'queryset': value, 'id':root and root.pk or "", 'name':name, 'attrs': attr_str}))) for root, value in roots.items()]), 'name': name, 'attrs': attr_str, 'error':rootserror} ) )
def parse(markup, sections=None): parser = EMarkupParser() parser.parse(markup) sections = parser.sections rendered_sections = SectionsDictionary() error_template = select_template(['markupchunks/error.html']) rendered_sections.vars.update(sections.vars) for section, chunks in sections.iteritems(): content_chunks = Section(chunks.name) content_chunks.vars.update(chunks.vars) for chunk in chunks: chunk_filename = "markupchunks/%s.html" % chunk.chunk_type.encode() chunk_template = select_template([chunk_filename, "markupchunks/paragraph.html"]) chunk_data = dict(vars=vars, chunk=chunk, content="\n".join(chunk)) try: chunk_html = chunk_template.render(Context(chunk_data)) except Exception, e: error = str(e) chunk_html = unicode(error_template.render(Context(dict(error=error)))) new_chunk = Chunk(chunk_html, chunk.chunk_type) new_chunk.vars.update(chunk.vars) content_chunks.append(new_chunk) rendered_sections[section] = content_chunks
def enqueue_30days_notification_for_closed_requests(helprequest): site = Site.objects.filter(id=settings.SITE_ID).first() subject = u'Seu pedido #%d foi atendido?' % helprequest.id from_email = settings.DEFAULT_FROM_EMAIL recipient = helprequest.requester tag = '30_days_closed_%d' % helprequest.id data = { 'helprequest': helprequest, 'recipient': recipient, 'site': site, } mail = QueuedMail.objects.filter(tag=tag).first() if mail: return mail with translation.override(set_language(recipient)): template_name = 'emails/30days_notification_for_closed_requests.html' html = select_template([template_name]).render(data) template_name = 'emails/30days_notification_for_closed_requests.txt' text = select_template([template_name]).render(data) return QueuedMail.objects.create( to=recipient, date=(now() + timedelta(30)).date(), subject=subject, html_content=html, text_content=text, tag=tag )
def dispatch(self, object, *args, **kwargs): self.object = object languages = [get_language(), self.fallback_language] receivers = self.get_receiver_emails() context = self.get_context() context.update(kwargs) attachments = self.get_attachments() template = self.template_name subject = select_template([ 'emails/{}.{}.subject'.format(template, lang) for lang in languages ]) plaintext = select_template([ 'emails/{}.{}.txt'.format(template, lang) for lang in languages ]) html = select_template([ 'emails/{}.{}.html'.format(template, lang) for lang in languages ]) mail = EmailMultiAlternatives( subject=subject.render(context).strip(), body=plaintext.render(context), from_email=settings.DEFAULT_FROM_EMAIL, to=receivers, ) if len(attachments) > 0: mail.mixed_subtype = 'related' for attachment in attachments: mail.attach(attachment) mail.attach_alternative(html.render(context), 'text/html') mail.send() return mail
def process(sections, context_data): if sections is None: return sections error_template = select_template(['blog/modules/error.html']) for section, chunks in sections.iteritems(): for chunk in chunks: module = chunk.vars.get('module') if module is not None: module_template = select_template(["blog/modules/%s.html"%module]) td = {} td.update(context_data) td.update( dict( vars = chunk.vars, content = chunk.text ) ) try: chunk_html = module_template.render(Context(td)) except Exception, e: error = str(e) chunk_html = unicode(error_template.render(Context(dict(error=error)))) chunk.text = chunk_html
def render(self, context, **options): template_pack = context['form_template_pack'] form = context['form'] bound_field = form[self.field_name] try: if 'template' in options: template = select_template(["{}/{}".format(template_pack, options['template'])]) elif 'widget' in options: widget_templates = [ '{}/fields/{}_{}.html'.format(template_pack, cls.__module__.split('.', 1)[0], cls.__name__.lower()) for cls in type(options['widget']).mro()[:-2]] template = select_template(widget_templates) else: template = _get_field_template(template_pack, bound_field.field) except TemplateDoesNotExist: # fallback to default field render warnings.warn("Unknown field and widget {} {}".format( bound_field.field.__class__, bound_field.field.widget.__class__)) return smart_text(bound_field) else: hidden_initial = '' if bound_field.field.show_hidden_initial: hidden_initial = bound_field.as_hidden(only_initial=True) context.push() try: context['bound_field'] = bound_field context['field'] = bound_field.field context['hidden_initial'] = hidden_initial return template.render(context.flatten()) finally: context.pop()
def enqueue_15days_notification_for_open_requests(helprequest): site = Site.objects.filter(id=settings.SITE_ID).first() subject = _('Did you answer the request #%d?') % helprequest.id from_email = settings.DEFAULT_FROM_EMAIL recipient = helprequest.bikeanjo tag = '15_days_open_%d' % helprequest.id data = { 'helprequest': helprequest, 'recipient': recipient, 'site': site, } mail = QueuedMail.objects.filter(tag=tag).first() if mail: return mail with translation.override(set_language(recipient)): template_name = 'emails/15days_notification_for_open_requests.html' html = select_template([template_name]).render(data) template_name = 'emails/15days_notification_for_open_requests.txt' text = select_template([template_name]).render(data) return QueuedMail.objects.create( to=recipient, date=(now() + timedelta(15)).date(), subject=subject, html_content=html, text_content=text, tag=tag )
def test_select_template_not_found(self): with self.assertRaises(TemplateDoesNotExist) as e: select_template(["template_loader/unknown.html", "template_loader/missing.html"]) self.assertEqual(e.exception.chain[0].tried[0][0].template_name, "template_loader/unknown.html") self.assertEqual(e.exception.chain[0].backend.name, "dummy") self.assertEqual(e.exception.chain[-1].tried[0][0].template_name, "template_loader/missing.html") self.assertEqual(e.exception.chain[-1].backend.name, "django")
def clean_style(self): style = self.cleaned_data.get('style') # Check if template for style exists: try: select_template(['aldryn_quote/plugins/%s/quote.html' % style]) except TemplateDoesNotExist: raise forms.ValidationError(_('Template not found')) return style
def test_select_template_string(self): with self.assertRaisesMessage( TypeError, "select_template() takes an iterable of template names but got a " "string: 'template_loader/hello.html'. Use get_template() if you " "want to load a single template by name.", ): select_template("template_loader/hello.html")
def clean_style(self): style = self.cleaned_data.get('style') # Check if template for style exists: try: select_template(['aldryn_gallery/plugins/%s/gallery.html' % style]) except TemplateDoesNotExist: raise forms.ValidationError("Not a valid style (Template does not exist)") return style
def get_template_names(self): template_name = "webpage/{}.html".format(self.kwargs.get("template", 'index')) try: loader.select_template([template_name]) template_name = "webpage/{}.html".format(self.kwargs.get("template", 'index')) except Exception as e: template_name = "webpage/index.html" return [template_name]
def test_select_template_not_found(self): with self.assertRaises(TemplateDoesNotExist) as e: select_template(["template_loader/unknown.html", "template_loader/missing.html"]) self.assertEqual( e.exception.tried[0][0].template_name, 'template_loader/unknown.html', ) self.assertEqual( e.exception.tried[-1][0].template_name, 'template_loader/missing.html', )
def changelist_view(self, request, extra_context=None): """Handle grouper filtering on the changelist""" if not request.GET: # redirect to grouper form when there's no GET parameters opts = self.model._meta return redirect( reverse("admin:{}_{}_grouper".format(opts.app_label, opts.model_name))) extra_context = extra_context or {} versionable = versionables.for_content(self.model._source_model) try: grouper = versionable.get_grouper_with_fallbacks( int(request.GET.get(versionable.grouper_field_name))) except (TypeError, ValueError): grouper = None else: if grouper is None: # no exception and no grouper, thus the querydict is invalid raise Http404 if grouper: # CAVEAT: as the breadcrumb trails expect a value for latest content in the template extra_context["latest_content"] = ({'pk': None}) extra_context.update( grouper=grouper, title=_('Displaying versions of "{grouper}"').format( grouper=grouper), ) breadcrumb_opts = self.model._source_model._meta extra_context["breadcrumb_opts"] = breadcrumb_opts # Check if custom breadcrumb template defined, otherwise # fallback on default breadcrumb_templates = [ "admin/djangocms_versioning/{app_label}/{model_name}/versioning_breadcrumbs.html" .format( app_label=breadcrumb_opts.app_label, model_name=breadcrumb_opts.model_name, ), "admin/djangocms_versioning/versioning_breadcrumbs.html", ] extra_context["breadcrumb_template"] = select_template( breadcrumb_templates) response = super().changelist_view(request, extra_context) # This is a slightly hacky way of accessing the instance of # the changelist that the admin changelist_view instantiates. # We do this to make sure that the latest content object is # picked from the same queryset as is being displayed in the # version table. if grouper and response.status_code == 200: # Catch the edge case where a grouper can have empty contents # when additional filters are present and the result set will be # empty for the additional values. try: response.context_data["latest_content"] = ( response.context_data["cl"].get_queryset(request).latest( "created").content) except ObjectDoesNotExist: pass return response
def get_template(self, context, **kwargs): template = select_template([ '{}/templatetags/cart-icon.html'.format(app_settings.APP_LABEL), 'shop/templatetags/cart-icon.html', ]) return template.template.name
def template_view(request): """ View that uses a template instance """ template = loader.select_template(["basic.html"]) return TemplateResponse(request, template)
def get(self, request, *args, **kwargs): entity = kwargs['entity'].lower() pk = kwargs['pk'] entity_model = ContentType.objects.get(app_label='apis_entities', model=entity).model_class() instance = get_object_or_404(entity_model, pk=pk) relations = ContentType.objects.filter(app_label='apis_relations', model__icontains=entity) side_bar = [] for rel in relations: print(str(rel)) match = str(rel).split() prefix = "{}{}-".format(match[0].title()[:2], match[1].title()[:2]) table = get_generic_relations_table(''.join(match), entity, detail=True) title_card = '' if match[0] == match[1]: title_card = entity.title() dict_1 = {'related_' + entity.lower() + 'A': instance} dict_2 = {'related_' + entity.lower() + 'B': instance} if 'apis_highlighter' in settings.INSTALLED_APPS: object_pre = rel.model_class( ).annotation_links.filter_ann_proj( request=request).filter(Q(**dict_1) | Q(**dict_2)) else: object_pre = rel.model_class().objects.filter( Q(**dict_1) | Q(**dict_2)) objects = [] for x in object_pre: objects.append(x.get_table_dict(instance)) else: if match[0].lower() == entity.lower(): title_card = match[1].title() else: title_card = match[0].title() dict_1 = {'related_' + entity.lower(): instance} if 'apis_highlighter' in settings.INSTALLED_APPS: objects = list( rel.model_class().annotation_links.filter_ann_proj( request=request).filter(**dict_1)) else: objects = list(rel.model_class().objects.filter(**dict_1)) tb_object = table(objects, prefix=prefix) tb_object_open = request.GET.get(prefix + 'page', None) RequestConfig(request, paginate={ "per_page": 10 }).configure(tb_object) side_bar.append( (title_card, tb_object, ''.join([x.title() for x in match]), tb_object_open)) object_lod = Uri.objects.filter(entity=instance) object_texts, ann_proj_form = get_highlighted_texts(request, instance) object_labels = Label.objects.filter(temp_entity=instance) tb_label = EntityDetailViewLabelTable(object_labels, prefix=entity.title()[:2] + 'L-') tb_label_open = request.GET.get('PL-page', None) side_bar.append(('Label', tb_label, 'PersonLabel', tb_label_open)) RequestConfig(request, paginate={"per_page": 10}).configure(tb_label) template = select_template([ 'apis_entities/detail_views/{}_detail_generic.html'.format(entity), 'apis_entities/detail_views/entity_detail_generic.html' ]) tei = getattr(settings, "APIS_TEI_TEXTS", []) if tei: tei = set(tei) & set([x.kind.name for x in instance.text.all()]) ceteicean_css = getattr(settings, "APIS_CETEICEAN_CSS", None) ceteicean_js = getattr(settings, "APIS_CETEICEAN_JS", None) openseadragon_js = getattr(settings, "APIS_OSD_JS", None) openseadragon_img = getattr(settings, "APIS_OSD_IMG_PREFIX", None) iiif_field = getattr(settings, "APIS_IIIF_WORK_KIND", None) if iiif_field: try: if "{}".format(instance.kind) == "{}".format(iiif_field): iiif = True else: iiif = False except AttributeError: iiif = False else: iiif = False iiif_server = getattr(settings, "APIS_IIIF_SERVER", None) iiif_info_json = instance.name no_merge_labels = [ x for x in object_labels if not x.label_type.name.startswith('Legacy') ] return HttpResponse( template.render(request=request, context={ 'entity_type': entity, 'object': instance, 'right_card': side_bar, 'no_merge_labels': no_merge_labels, 'object_lables': object_labels, 'object_texts': object_texts, 'object_lod': object_lod, 'tei': tei, 'ceteicean_css': ceteicean_css, 'ceteicean_js': ceteicean_js, 'iiif': iiif, 'openseadragon_js': openseadragon_js, 'openseadragon_img': openseadragon_img, 'iiif_field': iiif_field, 'iiif_info_json': iiif_info_json, 'iiif_server': iiif_server, }))
def render_field(self, field): """ Render a named field to HTML. """ try: field_instance = self.fields[field] except KeyError: raise NoSuchFormField("Could not resolve form field '%s'." % field) bf = forms.forms.BoundField(self, field_instance, field) output = '' if bf.errors: # If the field contains errors, render the errors to a <ul> # using the error_list helper function. # bf_errors = error_list([escape(error) for error in bf.errors]) bf_errors = ', '.join([e for e in bf.errors]) else: bf_errors = '' if bf.is_hidden: # If the field is hidden, add it at the top of the form self.prefix_fields.append(unicode(bf)) # If the hidden field has errors, append them to the top_errors # list which will be printed out at the top of form if bf_errors: self.top_errors.extend(bf.errors) else: # Find field + widget type css classes css_class = type(field_instance).__name__ + " " + type( field_instance.widget).__name__ # Add an extra class, Required, if applicable if field_instance.required: css_class += " required" if field_instance.help_text: # The field has a help_text, construct <span> tag help_text = '<span class="help-%s">%s</span>' % ( self.help_style, force_unicode(field_instance.help_text)) else: help_text = u'' field_hash = { 'class': mark_safe(css_class), 'label': mark_safe(bf.label or ''), 'help_text': mark_safe(help_text), 'field': field_instance, 'bf': mark_safe(unicode(bf)), 'bf_raw': bf, 'errors': mark_safe(bf_errors), 'field_type': mark_safe(field.__class__.__name__), 'label_id': bf._auto_id(), } if self.custom_fields.has_key(field): template = get_template(self.custom_fields[field]) else: template = select_template([ os.path.join( self.template_base, 'field_%s.html' % type(field_instance.widget).__name__.lower()), os.path.join(self.template_base, 'field_default.html'), ]) # Finally render the field output = template.render(Context(field_hash)) return mark_safe(output)
def render_flatpage(request, f): """ Internal interface to the flat page view. """ # If the page is a draft, only show it to users who are staff. if f.status == 'd' and not request.user.is_authenticated(): raise Http404 # 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: t = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: t = loader.get_template(DEFAULT_TEMPLATE) # Track pageviews (but not of owner). # if request.user != f.owner: # f.views += 1 # f.save() # # 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) # Create breadcrumb navigation links. # breadcrumb_urls = f.url.lstrip('/').rstrip('/').split('/') # breadcrumb_urls.insert(0, '/') # # for i, u in enumerate(breadcrumb_urls): # try: # Try and get a flatpage instance from the URL. # if u != '/': # u = '/%s/' % u # fp = FlatPage.objects.get(url__exact=u) # bt = fp.title # bu = fp.url # except: # Default to the URL slug, capitalized if no flatpage was found. # bt = u.capitalize() # bu = None # breadcrumbs += [{ # Contsruct a dictionary for the breadcrumb entity. # 'url': bu, # 'title': bt, # }] breadcrumb_urls = [] breadcrumbs = [] def trim_page(url): """Trim the last section off a URL.""" regex = re.compile(r'(?P<url>.*/)[-\w\.]+/?$') try: trimmed_url = regex.match(url).group('url') # Return the parent page except: trimmed_url = None # Return None to indicate no parent. return trimmed_url def do_trimming(url): """Perform the trimming operations recursively.""" breadcrumb_urls.append(url) trimmed_url = trim_page(url) if trimmed_url: do_trimming(trimmed_url) else: return True # Trim the flatpage's URL. do_trimming(f.url) # Reverse the list of breadcrumbs so the parent pages start first. breadcrumb_urls.reverse() # Loop through the list of pages and construct a list of url/title dictionaries # for each page to use in the templates. for i, u in enumerate(breadcrumb_urls): bn = '' bu = '' try: # Try and get a flatpage instance from the URL. # if u != '/': # u = '/%s/' % u fp = FlatPage.objects.get(url__exact=u) bn = fp.name bu = fp.url except: # Try to handle missing pages cleanly. regex = re.compile(r'.*/(?P<url>[-\w\.]+)/?$') try: # Default to the URL slug of the last segment of the URL # (capitalized) if no flatpage was found. This gives us an # OK default for missing pages. bn = regex.match(u).group('url') except: # Worst case scenario we show the URL as the title if we can't # grab the last bit of the URL... bn = u bn = bn.capitalize() # Capitalize it to make it look a little nicer. # Return None if the flatpage doesn't exist so we don't link to it, # because it would cause a 404 error if we did. bu = None breadcrumbs += [{ # Contsruct a dictionary for the breadcrumb entity. 'url': bu, 'name': bn, }] c = RequestContext(request, { 'flatpage': f, 'breadcrumbs': breadcrumbs, }) response = HttpResponse(t.render(c)) populate_xheaders(request, response, FlatPage, f.id) return response
def history_item(item): template_name = f"barriers/history/partials/{item.model}/{item.field}.html" default_template_name = "barriers/history/partials/default.html" item_template = select_template([template_name, default_template_name]) return item_template.render({'item': item})
def section(self, request, slug=None): try: section = Section.objects.get(slug=slug) except: return self.page(request, slug) order = request.GET.get('order', 'newest') if order == 'newest': order_by = '-published_at' else: order_by = 'published_at' query = request.GET.get('q', False) featured_articles = Article.objects.filter( section=section, is_published=True).order_by('-published_at') subsections = SubsectionHelper.get_subsections(section) featured_subsection = None featured_subsection_articles = None if subsections: featured_subsection = subsections[0] featured_subsection_articles = SubsectionHelper.get_featured_subsection_articles( featured_subsection, featured_articles) article_list = Article.objects.filter( section=section, is_published=True).order_by(order_by) if query: article_list = article_list.filter(headline__icontains=query) paginator = Paginator(article_list, 15) # Show 15 articles per page page = request.GET.get('page') try: articles = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. articles = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. articles = paginator.page(paginator.num_pages) context = { 'meta': { 'title': section.name, }, 'section': section, 'subsections': subsections, 'featured_subsection': { 'subsection': featured_subsection, 'articles': featured_subsection_articles }, 'type': 'section', 'featured_articles': { 'first': featured_articles[0], 'rest': featured_articles[1:4] }, 'articles': articles, 'order': order, 'q': query } t = loader.select_template( ['%s/%s' % (section.slug, 'section.html'), 'section.html']) return HttpResponse(t.render(context))
def article(self, request, section=None, slug=None): try: article = ArticleHelper.get_article(request, slug) except: raise Http404('Article could not be found.') article.add_view() breaking = ArticleHelper.get_breaking_news().exclude( id=article.id).first() # determine if user is viewing from mobile article_type = 'desktop' user_agent = get_user_agent(request) if user_agent.is_mobile: article_type = 'mobile' if article.template == 'timeline': timeline_tag = article.tags.filter(name__icontains='timeline-') timelineArticles = Article.objects.filter(tags__in=timeline_tag, is_published=True) temp = list( timelineArticles.values('parent_id', 'template_data', 'slug', 'headline', 'featured_image')) try: temp = sorted(temp, key=lambda article: json.loads(article[ 'template_data'])['timeline_date']) except: pass for i, a in enumerate(timelineArticles): try: temp[i][ 'featured_image'] = a.featured_image.image.get_thumbnail_url( ) except: temp[i]['featured_image'] = None article.timeline_articles = json.dumps(temp) article.timeline_title = list(timeline_tag)[0].name.replace( 'timeline-', '').replace('-', ' ') if article.template == 'soccer-nationals': teamData = NationalsHelper.prepare_data(article.content) article.content = teamData['content'] article.team_data = json.dumps(teamData['code']) if article.template == 'food-insecurity': data = FoodInsecurityHelper.prepare_data(article.content) article.content = data['content'] article.point_data = json.dumps( data['code']) if data['code'] is not None else None ref = request.GET.get('ref', None) dur = request.GET.get('dur', None) if not ArticleHelper.is_explicit(article): article.content = ArticleHelper.insert_ads(article.content, article_type) popular = ArticleHelper.get_popular()[:5] context = { 'title': '%s - %s' % (article.headline, self.SITE_TITLE), 'meta': ArticleHelper.get_meta(article), 'article': article, 'reading_list': ArticleHelper.get_reading_list(article, ref=ref, dur=dur), # 'suggested': lambda: ArticleHelper.get_random_articles(2, section, exclude=article.id), 'base_template': 'base.html', 'popular': popular, 'reading_time': ArticleHelper.get_reading_time(article), 'explicit': ArticleHelper.is_explicit(article), 'breaking': breaking, } template = article.get_template_path() t = loader.select_template([ '%s/%s' % (article.section.slug, template), template, 'article/default.html' ]) return HttpResponse(t.render(context))
def get_template(self): return select_template([ '{}/templatetags/cart-icon.html'.format(app_settings.APP_LABEL), 'shop/templatetags/cart-icon.html', ]).template
def get_render_template(self, context, instance, placeholder): template_names = [ '{}/checkout/process-bar.html'.format(app_settings.APP_LABEL), 'shop/checkout/process-bar.html', ] return select_template(template_names)
def get_template(template): if isinstance(template, (tuple, list)): return loader.select_template(template) return loader.get_template(template)
def render(self, template=None, suffix=None, extra_context={}, context_instance=None): """ Render the content using template search in the following order: 1. Supplied template 2. positions/render/<position>/<app><combine_string><model><combine_string><suffix>.html 3. positions/render/<position>/<app><combine_string><model>.html 4. positions/render/<app><combine_string><model>.html 5. positions/render/<position>/default.html 6. positions/render/default.html """ t, model, app = None, "", "" model = self.content_type.model.lower() app = self.content_type.app_label.lower() # The default render template path default_tmpl_path = 'positions/render/%s' # The supplied position template path pos_tmpl_path = default_tmpl_path % self.position.name + '/' # The default template default_tmpl = u'default.html' template_list = [] if template: template_list.append(template) if suffix: tmpl_name = '%s%s%s%s%s.html' % (app, settings.CONBINE_STRING, model, settings.CONBINE_STRING, suffix) template_list.append("".join([pos_tmpl_path, tmpl_name])) # set the content type template name tmpl_name = '%s%s%s.html' % (app, settings.CONBINE_STRING, model) # position_name + content type template template_list.append("".join([pos_tmpl_path, tmpl_name])) # default path + content type template template_list.append("".join([default_tmpl_path % tmpl_name])) # position name + default template template_list.append("".join([pos_tmpl_path, default_tmpl])) # default path + default template template_list.append(default_tmpl_path % default_tmpl) t = select_template(template_list) if not t: return None context = Context() if context_instance: context.update(context_instance.__dict__) context.update({'obj': self.content_object, 'content': self}) context.update(extra_context) return t.render(context)
def value(self, view: TemplateResponseMixin) -> Optional[datetime.datetime]: t = select_template(view.get_template_names()) local_tz = datetime.datetime.now().astimezone().tzinfo return datetime.datetime.fromtimestamp(os.stat(t.origin.name).st_mtime, tz=local_tz)
def about(request): context = {} c = RequestContext(request, context) t = select_template( ['regulations/custom-about.html', 'regulations/about.html']) return HttpResponse(t.render(c))
def get_render_template(self, context, instance, placeholder): # returns the first template that exists, falling back to bundled template return select_template( [instance.plugin_template, 'djangocms_embed/default.html'])
def select_theme_template(self, templates): return select_template(self.add_theme_to_template_names(templates))
def _get_notification_template(notification, pattern): template_names = [pattern % name for name in (notification.type.form_cls.__name__, 'base')] return loader.select_template(template_names)
def _get_template(self, value): if isinstance(value, (list, tuple)): return select_template(value) else: return get_template(value)
def get_render_template(self, context, instance, placeholder): return select_template([ '{}/catalog/product-list.html'.format(shop_settings.APP_LABEL), 'shop/catalog/product-list.html', ])
def assert_matching_template_origin(self, actual, expected_template_name): expected = select_template([expected_template_name]) self.assertEqual(actual.origin, expected.origin)
def index(request): context = {'products': Product.objects.filter(store=request.store)} t = select_template(['shoppingcart/' + request.store.sub_domain + \ '/index.html', 'shoppingcart/index.html']) return HttpResponse(t.render(RequestContext(request, context)))
def resolve_template(self, template_names): return loader.select_template(template_names)
def orders(request): orders = request.user.order_set.all() context = {'orders': orders} t = select_template(['shoppingcart/' + request.store.sub_domain + \ '/orders.html', 'shoppingcart/orders.html']) return HttpResponse(t.render(RequestContext(request, context)))
def get_render_template(self, context, instance, placeholder): return select_template([ '{}/checkout/forms-set.html'.format(app_settings.APP_LABEL), 'shop/checkout/forms-set.html', ])
def order_detail(request, id): order_details = OrderDetail.objects.filter(order=id) context = {'order_details': order_details} t = select_template(['shoppingcart/' + request.store.sub_domain + \ '/order_detail.html', 'shoppingcart/order_detail.html']) return HttpResponse(t.render(RequestContext(request, context)))
def test_select_template(self): for dirs in self.dirs_iter: template = loader.select_template(['test_dirs.html'], dirs=dirs) self.assertEqual(template.render(Context({})), 'spam eggs\n')
def get_template(self, meta): return loader.select_template([ f'renderers/iqy/{meta.app_label}/{meta.model_name}.txt', f'renderers/iqy/{meta.app_label}/iqy.txt', 'renderers/iqy.txt' ])
def home(request): """Home page.""" login_template = select_template(["login.html", "no_login.html"]) return render(request, "home.html", {"login_template": login_template})
def get_template(template): from django.template import loader if isinstance(template, (tuple, list)): return loader.select_template(template) return loader.get_template(template)