def load_template(self, template_name, template_dirs=None): source, file_path = self.load_template_source(template_name, template_dirs) if source.startswith("## mako\n"): # This is a mako template template = Template(filename=file_path, module_directory=self.module_directory, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8'], encoding_errors='replace', uri=template_name) return template, None else: # This is a regular template try: template = Engine.get_default().from_string(source) return template, None except ImproperlyConfigured: # Either no DjangoTemplates engine was configured -or- multiple engines # were configured, making the get_default() call above fail. raise except TemplateDoesNotExist: # If compiling the loaded template raises TemplateDoesNotExist, back off to # returning the source and display name for the requested template. # This allows for eventual correct identification of the actual template that does # not exist. return source, file_path
def get_template_path(template_name: str) -> Path: ''' Given a Django template path, return an absolute path to it. ''' # Note that we can't simply use the `origin` property of a Template # object, because, at least in Django 1.8, it seems this property # is None if TEMPLATE_DEBUG is disabled (and we want to be able to # render the styleguide in non-debug instances). candidates = [] for loader in Engine.get_default().template_loaders: for candidate in loader.get_template_sources(template_name): candidates.append(candidate) path = None for candidate in candidates: if os.path.exists(candidate.name): path = candidate.name break if path is None: raise ValueError(f'Template {template_name} not found') return Path(path)
def get_plugin_index_data(base_plugin, request): searchable_text = [] instance, plugin_type = base_plugin.get_plugin_instance() if instance is None: return searchable_text search_fields = getattr(instance, 'search_fields', []) if not bool(search_fields): context = RequestContext(request) updates = {} engine = Engine.get_default() for processor in engine.template_context_processors: updates.update(processor(context.request)) context.dicts[context._processors_index] = updates plugin_contents = instance.render_plugin(context=context) if plugin_contents: searchable_text = get_cleaned_text(plugin_contents) else: values = (get_field_value(instance, field) for field in search_fields) for value in values: cleaned_bits = get_cleaned_text(value or '') searchable_text.extend(cleaned_bits) return searchable_text
def render_plugin_in_context(self, plugin, context=None): """ Render a plugin, passing on the template context into the plugin's template (if the plugin uses a template renderer). """ if plugin.__class__ not in self._renderers: raise PluginNotRegistered("Plugin %s is not registered" % plugin._meta.label_lower) plugin_template, plugin_context = self._renderers[plugin.__class__] if plugin_template is None: return (plugin_context(plugin) if callable(plugin_context) else plugin_context) # Simple string renderer if context is None: context = Context() if callable(plugin_template): plugin_template = plugin_template(plugin) if callable(plugin_context): plugin_context = plugin_context(plugin, context) if not hasattr(plugin_template, "render"): # Quacks like a template? try: engine = context.template.engine except AttributeError: engine = Engine.get_default() if isinstance(plugin_template, (list, tuple)): plugin_template = engine.select_template(plugin_template) else: plugin_template = engine.get_template(plugin_template) with context.push(plugin_context): return plugin_template.render(context)
def test_include_template_none(self): engine = Engine.get_default() outer_temp = engine.from_string('{% include var %}') ctx = Context({'var': None}) msg = 'No template names provided' with self.assertRaisesMessage(TemplateDoesNotExist, msg): outer_temp.render(ctx)
def load_template(self, template_name, template_dirs=None): source, file_path = self.load_template_source(template_name, template_dirs) # In order to allow dynamic template overrides, we need to cache templates based on their absolute paths # rather than relative paths, overriding templates would have same relative paths. module_directory = self.module_directory.rstrip( "/") + "/{dir_hash}/".format(dir_hash=hash(file_path)) if source.startswith("## mako\n"): # This is a mako template template = Template(filename=file_path, module_directory=module_directory, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8'], encoding_errors='replace', uri=template_name, engine=engines['mako']) return template, None else: # This is a regular template try: template = Engine.get_default().from_string(source) return template, None except ImproperlyConfigured: # Either no DjangoTemplates engine was configured -or- multiple engines # were configured, making the get_default() call above fail. raise except TemplateDoesNotExist: # If compiling the loaded template raises TemplateDoesNotExist, back off to # returning the source and display name for the requested template. # This allows for eventual correct identification of the actual template that does # not exist. return source, file_path
def tableHtml(search_obj, header=True, footer=False, table_class=""): """Takes a SearchBase object and returns an HTML table""" error = None table_info = None table_data = None engine = Engine.get_default() template = engine.get_template('targetsearch/table.html') try: table_info = search_obj.table_info table_data = search_obj.get_results() except Exception as e: error = str(e) context = { 'error': error, 'header': header, 'footer': footer, 'table_info': table_info, 'table_data': table_data, 'table_class': table_class, } return template.render(Context(context))
def load_template(self, template_name, template_dirs=None): source, file_path = self.load_template_source(template_name, template_dirs) if source.startswith("## mako\n"): # This is a mako template template = Template(filename=file_path, module_directory=self.module_directory, input_encoding='utf-8', output_encoding='utf-8', uri=template_name) return template, None else: # This is a regular template try: template = Engine.get_default().from_string(source) return template, None except ImproperlyConfigured: # Either no DjangoTemplates engine was configured -or- multiple engines # were configured, making the get_default() call above fail. raise except TemplateDoesNotExist: # If compiling the loaded template raises TemplateDoesNotExist, back off to # returning the source and display name for the requested template. # This allows for eventual correct identification of the actual template that does # not exist. return source, file_path
def get_winner_description( self, obj: models.CompetitionPrize ): engine = Engine.get_default() string_template = obj.prize_attribution_template try: winner = models.Winner.objects.get( participant__user=self.context.get("user"), participant__competition=obj.competition ) except models.Winner.DoesNotExist: result = string_template else: score = winner.participant.get_score() formatted_score = ", ".join( "{}: {:0.3f}".format(criterium.value, value) for criterium, value in score.items() ) context = Context({ "rank": winner.rank, "score": formatted_score, }) if "humanize" not in string_template: string_template = "{% load humanize %}" + string_template template = engine.from_string(string_template) result = template.render(context) return result
def check_for_context_processors(app_configs, **kwargs): errors = [] # Pattern from django.contrib.admin.checks try: default_template_engine = Engine.get_default() except Exception: # Skip this non-critical check: # 1. if the user has a non-trivial TEMPLATES setting and Django # can't find a default template engine # 2. if anything goes wrong while loading template engines, in # order to avoid raising an exception from a confusing location # Catching ImproperlyConfigured suffices for 1. but 2. requires # catching all exceptions. pass else: context_processors = default_template_engine.context_processors for context_processor in REQUIRED_CONTEXT_PROCESSORS: if context_processor[0] not in context_processors: errors.append( Error( "needs %s in TEMPLATES[*]['OPTIONS']['context_processors']" % context_processor[0], id="wiki.%s" % context_processor[1], ) ) return errors
def load_template(self, template_name, template_dirs=None): source, file_path = self.load_template_source(template_name, template_dirs) # In order to allow dynamic template overrides, we need to cache templates based on their absolute paths # rather than relative paths, overriding templates would have same relative paths. module_directory = self.module_directory.rstrip("/") + "/{dir_hash}/".format(dir_hash=hash(file_path)) if source.startswith("## mako\n"): # This is a mako template template = Template(filename=file_path, module_directory=module_directory, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8'], encoding_errors='replace', uri=template_name, engine=engines['mako']) return template, None else: # This is a regular template try: template = Engine.get_default().from_string(source) return template, None except ImproperlyConfigured: # Either no DjangoTemplates engine was configured -or- multiple engines # were configured, making the get_default() call above fail. raise except TemplateDoesNotExist: # If compiling the loaded template raises TemplateDoesNotExist, back off to # returning the source and display name for the requested template. # This allows for eventual correct identification of the actual template that does # not exist. return source, file_path
def _render_menu(slug, context, html_template=None, css_class=None): """Helper function to render a maneu. It takes a menu slug, a context, a template name, any CSS class and renders the given menu using the given attributes. """ try: links = None if isinstance(slug, template.Variable): slug = slug.resolve(context) if isinstance(html_template, template.Variable): html_template = html_template.resolve(context) if isinstance(css_class, template.Variable): css_class = css_class.resolve(context) menu = Menu.objects.get(slug=slug) links = menu.links.all() for link in links: _calculate_link_params(link, context) html_template = html_template or menu.template_name or settings.MENU_DEFAULT_TEMPLATE html_template = ("%s" % html_template).replace('"', '').replace("'", "") html_template = Engine.get_default().get_template(html_template) with context.push(slug=slug, links=links, css_class=css_class): result = html_template.render(context) return result except Menu.DoesNotExist: pass return ""
def render_region(context, region_slug, template_name=None): """Renders the region identified by the given slug with the given template. It takes the following arguments: * region_slug -- Univoque slug which identifies the region that should be rendered. * template_name -- Template to be used to render the region. [default: pluggets/region.html] Example usage: {% render_region region_slug template_name %} """ if isinstance(region_slug, template.Variable): region_slug = region_slug.resolve(context) if isinstance(template_name, template.Variable): template_name = template_name.resolve(context) result = "" try: region = Region.objects.get(slug=region_slug) html_template = Engine.get_default().get_template( template_name or settings.REGION_DEFAULT_TEMPLATE) with context.push(region=region): result = html_template.render(context) except ObjectDoesNotExist: pass return result
def get_template_path(template_name: str) -> Path: ''' Given a Django template path, return an absolute path to it. ''' # Note that we can't simply use the `origin` property of a Template # object, because, at least in Django 1.8, it seems this property # is None if TEMPLATE_DEBUG is disabled (and we want to be able to # render the styleguide in non-debug instances). candidates = [] for loader in Engine.get_default().template_loaders: for candidate in loader.get_template_sources(template_name): candidates.append(candidate) path = None for candidate in candidates: if os.path.exists(candidate.name): path = candidate.name break if path is None: raise ValueError(f'Template {template_name} not found') return Path(path)
def _render_plugin(request, plugin): context = RequestContext(request) if not LTE_DJANGO_1_7: from django.template import Engine # On Django <= 1.7, the RequestContext class would call # all context processors and update the context on initialization. # On Django >= 1.8 the logic to update the context # from context processors is now tied to the bind_template # context manager. updates = {} engine = Engine.get_default() for processor in engine.template_context_processors: updates.update(processor(context.request)) context.dicts[context._processors_index] = updates try: from cms.plugin_rendering import ContentRenderer except ImportError: # djangoCMS < 3.4 compatibility pass else: context['cms_content_renderer'] = ContentRenderer(request=request) return plugin.render_plugin(context)
def find_all_templates(pattern='*.html'): """ Finds all Django templates matching given glob in all TEMPLATE_LOADERS :param str pattern: `glob <http://docs.python.org/2/library/glob.html>`_ to match .. important:: At the moment egg loader is not supported. """ templates = [] template_loaders = flatten_template_loaders(settings.TEMPLATE_LOADERS) for loader_name in template_loaders: module, klass = loader_name.rsplit('.', 1) if loader_name in ( 'django.template.loaders.app_directories.Loader', 'django.template.loaders.filesystem.Loader', ): loader_class = getattr(import_module(module), klass) if getattr(loader_class, '_accepts_engine_in_init', False): loader = loader_class(Engine.get_default()) else: loader = loader_class() for dir in loader.get_template_sources(''): for root, dirnames, filenames in os.walk(dir): for basename in filenames: filename = os.path.join(root, basename) rel_filename = filename[len(dir)+1:] if fnmatch.fnmatch(filename, pattern) or \ fnmatch.fnmatch(basename, pattern) or \ fnmatch.fnmatch(rel_filename, pattern): templates.append(rel_filename) else: LOGGER.debug('%s is not supported' % loader_name) return sorted(set(templates))
def test_get_hook_html(self, mock_get_backends): good = MagicMock() good.slug = "good" good.get_hook_template.return_value = "good/frame_top.html" mock_get_backends.return_value = [BadBackend(), good] real_get_template = Engine.get_default().get_template def get_template(name): if name == "good/frame_top.html": return Template('<script>alert("good")</script>\n') elif name == "bad/frame_top.html": return Template('<script>alert("bad")</script>\n') else: return real_get_template(name) with patch("django.template.engine.Engine.get_template", wraps=get_template): self.login(self.admin) response = self.client.get(reverse("orgs.org_home")) self.assertContains( response, """<!-- begin hook for bad --> <script>alert("bad")</script> <!-- end hook for bad --> <!-- begin hook for good --> <script>alert("good")</script> <!-- end hook for good -->""", )
def get_default_content(self): engine = Engine.get_default() loader = TemplateSourceLoader(engine) try: return loader.get_source(self.title) except Exception as e: logger.error('Error loading template %s. Details: %s ', self.title, e) return ''
def django_process(src, filename): # actually use the django loader to get the sources loader = Loader(Engine.get_default(), config['TEMPLATES'][0]['OPTIONS']['loaders']) t = loader.get_template(filename) ctx = django.template.Context() return t.render(ctx)
def parametise_label(widget_or_parametisation, view, text): if text is None: return None context = Context(view.my_properties()) eng = Engine.get_default() template = eng.from_string(text) rendered = template.render(context) return rendered
def wrapper(*args, **kwargs): engine = Engine.get_default() initial_setting = engine.debug try: engine.debug = True return clean_func(*args, **kwargs) finally: engine.debug = initial_setting
def django_process(src, filename): # actually use the django loader to get the sources loader = Loader( Engine.get_default(), config['TEMPLATES'][0]['OPTIONS']['loaders'] ) t = loader.get_template(filename) ctx = django.template.Context() return t.render(ctx)
def get_default_content(self): engine = Engine.get_default() loader = TemplateSourceLoader(engine) try: return loader.get_source(self.title) except Exception as e: logger.error('Error loading template %s. Details: %s ', self.title, e) return ''
def render_model_list(context, object_list, field_list=[], template_name=None, uid=""): """Renders a table with given fields for all given model instances. It takes three optional arguments: * field_list -- The list of field names to be rendered [default: all]. * template_name -- Template that renders the list [default: elements/table_list.html] * uid -- An universal ID for this model list (must be unique in the template context). Example tag usage: {% render_model_list object_list [fields] [template_name] %} """ if not isinstance(object_list, models.query.QuerySet): return "" if not field_list: field_list = [] prefix = "" if uid: prefix = "%s_" % uid model = object_list.model fields = [model._meta.get_field(n) for n in field_list] or model._meta.fields filters = dict([(f.attname, ("", "")) for f in fields]) filters.update(context.get("%slist_filter_by" % prefix, None) or {}) headers = [{ "name": f.verbose_name, "attname": f.attname, "type": get_field_type(f), "filter": { "expr": filters[f.attname][0], "value": filters[f.attname][1] } } for f in fields] rows = [{ "object": o, "fields": [f.value_to_string(o) for f in fields] } for o in object_list] table = { "uid": uid, "order_by": object_list.query.order_by, "headers": headers, "rows": rows } html_template = Engine.get_default().get_template( template_name or settings.MODEL_LIST_DEFAULT_TEMPLATE) with context.push(table=table): result = html_template.render(context) return result
def _decorated(*args, **kwargs): # pylint: disable=missing-docstring with override_settings(COMPREHENSIVE_THEME_DIR=theme_dir, **changes['settings']): default_engine = Engine.get_default() dirs = default_engine.dirs[:] with edxmako.save_lookups(): for template_dir in changes['template_paths']: edxmako.paths.add_lookup('main', template_dir, prepend=True) dirs.insert(0, template_dir) with patch.object(default_engine, 'dirs', dirs): return func(*args, **kwargs)
def template_source_loaders(self): if not self._template_source_loaders: loaders = [] # for loader_name in settings.FLAVOURS_TEMPLATE_LOADERS: for loader_name in ['django.template.loaders.app_directories.Loader']: loader = Engine.get_default().find_template_loader(loader_name) if loader is not None: loaders.append(loader) self._template_source_loaders = tuple(loaders) return self._template_source_loaders
def _decorated(*args, **kwargs): # pylint: disable=missing-docstring with override_settings(COMPREHENSIVE_THEME_DIR=theme_dir, **changes['settings']): default_engine = Engine.get_default() dirs = default_engine.dirs[:] with edxmako.save_lookups(): for template_dir in changes['template_paths']: edxmako.paths.add_lookup('main', template_dir, prepend=True) dirs.insert(0, template_dir) with patch.object(default_engine, 'dirs', dirs): return func(*args, **kwargs)
def render_plugin_in_context(self, plugin, context=None): """ Render a plugin, passing on the template context into the plugin's template (if the plugin uses a template renderer). The template tags in ``feincms3_renderer`` assume that the renderer instance is available as ``renderer`` inside the context. A suitable view would look as follows:: def page_detail(request, slug): page = get_object_or_404(Page, slug=slug) return render(request, 'page.html', { 'page': page, 'contents': contents_for_item(page, renderer.plugins()), 'renderer': renderer, }) The template itself should contain the following snippet:: {% load feincms3_renderer %} {% block content %} <h1>{{ page.title }}</h1> <main> {% for plugin in contents.main %} {% render_plugin plugin %} {% endfor %} </main> <aside> {# or simply #} {% render_plugins contents.sidebar %} </aside> {% endblock %} """ plugin_template, plugin_context = self._renderers[plugin.__class__] if plugin_template is None: return plugin_context(plugin) # Simple string renderer if context is None: context = Context() if callable(plugin_template): plugin_template = plugin_template(plugin) if callable(plugin_context): plugin_context = plugin_context(plugin, context) if not hasattr(plugin_template, 'render'): # Quacks like a template? try: engine = context.template.engine except AttributeError: engine = Engine.get_default() if isinstance(plugin_template, (list, tuple)): plugin_template = engine.select_template(plugin_template) else: plugin_template = engine.get_template(plugin_template) with context.push(plugin_context): return plugin_template.render(context)
def test_include_template_iterable(self): engine = Engine.get_default() outer_temp = engine.from_string('{% include var %}') tests = [ ('admin/fail.html', 'index.html'), ['admin/fail.html', 'index.html'], ] for template_names in tests: with self.subTest(template_names): output = outer_temp.render(Context({'var': template_names})) self.assertEqual(output, 'index\n')
def _render_via_django(): from django.template import Engine context = RequestContext(request) updates = {} engine = Engine.get_default() for processor in engine.template_context_processors: updates.update(processor(context.request)) context.dicts[context._processors_index] = updates return plugin.render_plugin(context)
def test_include_template_iterable(self): engine = Engine.get_default() outer_temp = engine.from_string("{% include var %}") tests = [ ("admin/fail.html", "index.html"), ["admin/fail.html", "index.html"], ] for template_names in tests: with self.subTest(template_names): output = outer_temp.render(Context({"var": template_names})) self.assertEqual(output, "index\n")
def __init__(self, *args, **kwargs): super(EmailTemplateAdminForm, self).__init__(*args, **kwargs) self.fields['preview'].widget = forms.Textarea(attrs={'readonly': 'readonly', 'rows': 30, 'cols': 120}) if self.initial: engine = Engine.get_default() loader = TemplateSourceLoader(engine) try: self.fields['preview'].initial = loader.get_source( os.path.join("emailtemplates", self.initial['title'])) except Exception, e: logger.error('Load template error. Details: %s', e)
def _render_via_django(): from django.template import Engine context = RequestContext(request) updates = {} engine = Engine.get_default() for processor in engine.template_context_processors: updates.update(processor(context.request)) context.dicts[context._processors_index] = updates return plugin.render_plugin(context)
def get_plugin_index_data(base_plugin, request): text_bits = [] instance, plugin_type = base_plugin.get_plugin_instance() if instance is None: # this is an empty plugin return text_bits search_fields = getattr(instance, "search_fields", []) if hasattr(instance, "search_fulltext"): # check if the plugin instance has search enabled search_contents = instance.search_fulltext elif hasattr(base_plugin, "search_fulltext"): # now check in the base plugin instance (CMSPlugin) search_contents = base_plugin.search_fulltext elif hasattr(plugin_type, "search_fulltext"): # last check in the plugin class (CMSPluginBase) search_contents = plugin_type.search_fulltext else: # disabled if there's search fields defined, # otherwise it's enabled. search_contents = not bool(search_fields) if search_contents: context = RequestContext(request) if not DJANGO_1_7: from django.template import Engine # On Django <= 1.7, the RequestContext class would call # all context processors and update the context on initialization. # On Django >= 1.8 the logic to update the context # from context processors is now tied to the bind_template # context manager. updates = {} engine = Engine.get_default() for processor in engine.template_context_processors: updates.update(processor(context.request)) context.dicts[context._processors_index] = updates plugin_contents = instance.render_plugin(context=context) if plugin_contents: text_bits = get_cleaned_bits(plugin_contents) else: values = (get_field_value(instance, field) for field in search_fields) for value in values: cleaned_bits = get_cleaned_bits(value or "") text_bits.extend(cleaned_bits) return text_bits
def get_plugin_index_data(base_plugin, request): text_bits = [] instance, plugin_type = base_plugin.get_plugin_instance() if instance is None: # this is an empty plugin return text_bits search_fields = getattr(instance, 'search_fields', []) if hasattr(instance, 'search_fulltext'): # check if the plugin instance has search enabled search_contents = instance.search_fulltext elif hasattr(base_plugin, 'search_fulltext'): # now check in the base plugin instance (CMSPlugin) search_contents = base_plugin.search_fulltext elif hasattr(plugin_type, 'search_fulltext'): # last check in the plugin class (CMSPluginBase) search_contents = plugin_type.search_fulltext else: # disabled if there's search fields defined, # otherwise it's enabled. search_contents = not bool(search_fields) if search_contents: context = RequestContext(request) if not DJANGO_1_7: from django.template import Engine # On Django <= 1.7, the RequestContext class would call # all context processors and update the context on initialization. # On Django >= 1.8 the logic to update the context # from context processors is now tied to the bind_template # context manager. updates = {} engine = Engine.get_default() for processor in engine.template_context_processors: updates.update(processor(context.request)) context.dicts[context._processors_index] = updates plugin_contents = instance.render_plugin(context=context) if plugin_contents: text_bits = get_cleaned_bits(plugin_contents) else: values = (get_field_value(instance, field) for field in search_fields) for value in values: cleaned_bits = get_cleaned_bits(value or '') text_bits.extend(cleaned_bits) return text_bits
def send_email(self): from .views import UUID messages_sent, body = None, None if self.is_valid() and self.order_token: email_address = self.cleaned_data['email_address'] subject = 'Your Receipt for LibreShop Order %s!' % self.order_token try: # Get Order from specified token. order = Order.objects.get(token=self.order_token) # Get the latest Transaction. transaction = Transaction.objects.filter(order=order).latest() except (Order.DoesNotExist, Transaction.DoesNotExist) as e: pass else: # Load the default template engine. TemplateEngine = Engine.get_default() # Render a context to the template specified in `template_name`. template = TemplateEngine.get_template(self.template_name) context = Context({ 'order': order, 'purchases': order.purchases.all(), 'transaction': transaction }) body = template.render(context) message = EmailMessage(subject=subject, body=body, from_email=settings.DEFAULT_FROM_EMAIL, to=[email_address], bcc=[], connection=None, attachments=None, headers=None, cc=None, reply_to=None) messages_sent = message.send() if messages_sent: Communication.objects.create( order=order, from_email=settings.DEFAULT_FROM_EMAIL, to_email=email_address, subject=subject, body=body) return bool(messages_sent)
def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) proposals = models.EventProposal.objects.filter( camp=self.camp).select_related('user', 'event') context['proposals'] = proposals engine = Engine.get_default() template = engine.get_template('control/proposal_overview.csv') csv = template.render(Context(context)) context['csv'] = csv return context
def check_for_context_processors(app_configs, **kwargs): errors = [] context_processors = Engine.get_default().context_processors for context_processor in REQUIRED_CONTEXT_PROCESSORS: if context_processor[0] not in context_processors: errors.append( Error( "needs %s in TEMPLATE['OPTIONS']['context_processors']" % context_processor[0], id='wiki.%s' % context_processor[1], )) return errors
def new_product(request): cls_default_msgs = { 'not_signed_in': 'You must be signed in to list your product', 'invalid_param': 'Invalid parameters. \ Please make sure you fill in all fields', } product_form = ProductForm() ImageFormSet = modelformset_factory(ProductPhoto, form=ImageForm, extra=3) userid = request.user.id form = ProductForm(request.POST or None) formset = ImageFormSet(request.POST, request.FILES, queryset=ProductPhoto.objects.none()) if request.POST: if request.user.is_authenticated(): if form.is_valid() and formset.is_valid(): product = form.save(commit=False) product.owner = request.user product.user_id = userid product.active = True product.slug = form.cleaned_data['name'].replace(" ", "") product.date_created = timezone.now() product.date_last_modified = timezone.now() product.save() for form in formset: if form.cleaned_data: image = form.cleaned_data['image'] photo = ProductPhoto(product=product, image=image) photo.user_id = userid photo.save() return render(request, "updated_product.html", {"product": product}) else: # Set error context error_msg = cls_default_msgs['not_signed_in'] messages.add_message(request, messages.INFO, error_msg, form.errors) # Set template template = Engine.get_default().get_template('login.html') # Set result in RequestContext context = RequestContext(request) return HttpResponse(template.render(context)) return render( request, 'products/new_product.html', { 'form': form, 'formset': ImageFormSet(queryset=ProductPhoto.objects.none()) })
def render_html(message, etype, img_url, sender, template): """Docstring""" print(template) engine = Engine.get_default() s = MailTemplate.objects.get(pk=template).template.read().decode() template = engine.from_string(s) html = template.render(Context({ 'message': bleach.clean(message, tags=bleach.sanitizer.ALLOWED_TAGS + ['p'], strip=True), 'etype': etype, 'img_url': img_url, 'from': sender, })) return transform(html)
def _render_action_email(action, attendee, outreach_email, template): if isinstance(template, str): template = Engine.get_default().get_template(template) ctx = { "action": action, "contact": attendee.contact, "base_url": base_url(), "outreach_email": outreach_email, } msg_body = template.render(Context(ctx)) return msg_body
def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) proposals = models.EventProposal.objects.filter( camp=self.camp ).select_related('user', 'event') context['proposals'] = proposals engine = Engine.get_default() template = engine.get_template('control/proposal_overview.csv') csv = template.render(Context(context)) context['csv'] = csv return context
def get_plugin_index_data(base_plugin, request): text_bits = [] instance, plugin_type = base_plugin.get_plugin_instance() if instance is None or instance.plugin_type in EXCLUDED_PLUGINS: # this is an empty plugin or excluded from search return text_bits search_fields = getattr(instance, 'search_fields', []) if hasattr(instance, 'search_fulltext'): # check if the plugin instance has search enabled search_contents = instance.search_fulltext elif hasattr(base_plugin, 'search_fulltext'): # now check in the base plugin instance (CMSPlugin) search_contents = base_plugin.search_fulltext elif hasattr(plugin_type, 'search_fulltext'): # last check in the plugin class (CMSPluginBase) search_contents = plugin_type.search_fulltext else: # disabled if there's search fields defined, # otherwise it's enabled. search_contents = not bool(search_fields) if search_contents: context = RequestContext(request) updates = {} engine = Engine.get_default() for processor in engine.template_context_processors: updates.update(processor(context.request)) context.dicts[context._processors_index] = updates try: # django-cms>=3.5 renderer = request.toolbar.content_renderer except AttributeError: # django-cms>=3.4 renderer = context.get('cms_content_renderer') plugin_contents = _render_plugin(instance, context, renderer) if plugin_contents: text_bits = get_cleaned_bits(plugin_contents) else: values = (get_field_value(instance, field) for field in search_fields) for value in values: cleaned_bits = get_cleaned_bits(value or '') text_bits.extend(cleaned_bits) return text_bits
def find_all_templates(pattern='*.html'): """ Finds all Django templates matching given glob in all TEMPLATE_LOADERS :param str pattern: `glob <http://docs.python.org/2/library/glob.html>`_ to match .. important:: At the moment egg loader is not supported. """ templates = [] template_loaders = flatten_template_loaders(get_template_loaders()) if template_loaders: for loader_name in template_loaders: module, klass = loader_name.rsplit('.', 1) if loader_name in ( 'django.template.loaders.app_directories.Loader', 'django.template.loaders.filesystem.Loader', ): loader_class = getattr(import_module(module), klass) try: loader = loader_class(Engine.get_default()) except BaseException: loader = loader_class() for dir in loader.get_template_sources(''): dir = "%s" % dir for root, dirnames, filenames in os.walk(dir): for basename in filenames: filename = os.path.join(root, basename) rel_filename = filename[len(dir) + 1:] if fnmatch.fnmatch(filename, pattern) or \ fnmatch.fnmatch(basename, pattern) or \ fnmatch.fnmatch(rel_filename, pattern): templates.append(filename) else: logger.debug('{0!s} is not supported'.format(loader_name)) else: try: from django.template.loader import engines for engine in engines.all(): for dir in engine.dirs: for root, dirnames, filenames in os.walk(dir): for basename in filenames: filename = os.path.join(root, basename) rel_filename = filename[len(dir) + 1:] if fnmatch.fnmatch(filename, pattern) or \ fnmatch.fnmatch(basename, pattern) or \ fnmatch.fnmatch(rel_filename, pattern): templates.append(filename) except BaseException: pass return sorted(set(templates))
def parametise_label(widget_or_parametisation, view, text): if text is None: return None if widget_or_parametisation: if isinstance(widget_or_parametisation, Parametisation): param = widget_or_parametisation else: param = widget_or_parametisation.parametisation else: param = None if param: context = Context(view.properties()) eng = Engine.get_default() template = eng.from_string(text) return template.render(context) else: return text
def find_all_templates(pattern='*.html'): """ Finds all Django templates matching given glob in all TEMPLATE_LOADERS :param str pattern: `glob <http://docs.python.org/2/library/glob.html>`_ to match .. important:: At the moment egg loader is not supported. """ templates = [] engine = Engine.get_default() template_loaders = flatten_template_loaders(engine.loaders) for loader_name in template_loaders: module, klass = loader_name.rsplit('.', 1) if loader_name in ( 'django.template.loaders.app_directories.Loader', 'django.template.loaders.filesystem.Loader', ): loader_class = getattr(import_module(module), klass) if getattr(loader_class, '_accepts_engine_in_init', False): loader = loader_class(engine) else: try: loader = loader_class() except TypeError: # probably Django which is modern enough to require # engine being passed to the init, but has since removed # _accepts_engine_in_init loader = loader_class(engine) for directory in loader.get_template_sources(''): # In 1.9, Origin is always set. # https://docs.djangoproject.com/en/1.9/releases/1.9/#template-loaderorigin-and-stringorigin-are-removed if hasattr(directory, 'loader_name'): directory = directory.name for root, dirnames, filenames in os.walk(directory): for basename in filenames: filename = os.path.join(root, basename) rel_filename = filename[len(directory)+1:] if fnmatch.fnmatch(filename, pattern) or \ fnmatch.fnmatch(basename, pattern) or \ fnmatch.fnmatch(rel_filename, pattern): templates.append(rel_filename) else: LOGGER.debug('{0!s} is not supported'.format(loader_name)) return sorted(set(templates))
def new_center(request): cls_default_msgs = { 'not_signed_in': 'You must be signed in to list your event center', 'invalid_param': 'Invalid parameters. \ Please make sure you fill in all fields', } center_form = CenterForm() ImageFormSet = modelformset_factory(CenterPhoto, form=ImageForm, extra=3) userid = request.user.id form = CenterForm(request.POST or None) formset = ImageFormSet(request.POST, request.FILES, queryset=CenterPhoto.objects.none()) if request.POST: if request.user.is_authenticated(): if form.is_valid() and formset.is_valid(): center = form.save(commit=False) center.owner = request.user center.user_id = userid center.active = True center.slug = form.cleaned_data['name'].replace(" ", "") center.date_created = timezone.now() center.date_last_modified = timezone.now() center.save() for form in formset.cleaned_data: image = form['image'] photo = CenterPhoto(center=center, image=image) photo.user_id = userid photo.save() return render(request, "updated_center.html", {"center":center}) else: # Set error context error_msg = cls_default_msgs['not_signed_in'] messages.add_message(request, messages.INFO, error_msg, form.errors) # Set template template = Engine.get_default().get_template('login.html') # Set result in RequestContext context = RequestContext(request) return HttpResponse(template.render(context)) return render(request, 'centers/new_center.html', {'form': form, 'formset': ImageFormSet(queryset=CenterPhoto.objects.none())})
def get_template_from_string(self, tpl): return Engine.get_default().from_string(tpl)
def booking_view(request, slug, model_class=Center, form_class=BookingForm, template_name='centers/booking_form.html'): cls_default_msgs = { 'not_signed_in': 'You must be signed in to book this event center', } center = get_object_or_404(model_class, slug=slug) args = dict() if request.POST: form = form_class(request.user, center, request.POST) if request.user.is_authenticated(): if form.is_valid(): booking = form.save(commit=False) booking.center = center booking.user_id = request.user.id booking.is_approved = False start_date = form.cleaned_data.get("booking_start_date") end_date = form.cleaned_data.get("booking_end_date") if end_date < start_date: msg = u"The start date cannot be later than the end date. Please input an end date after the selected start date." messages.add_message(request, messages.INFO, msg, form.errors) template = Engine.get_default().get_template(template_name) context = RequestContext(request) return HttpResponse(template.render(context)) booking.save() args["slug"] = slug args["center"] = center.name # compose the email booking_email_context = RequestContext( request, {'username': booking.customer_name, 'center': center.name, 'booking': booking.booking_start_date, }, ) receipient = str(booking.customer_email) subject, from_email, to = 'TheEventDiary: Booking Recieved', EMAIL_SENDER, receipient html_content=loader.get_template('centers/booking_email.html').render(booking_email_context) text_content=loader.get_template('centers/booking_email.txt').render(booking_email_context) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") response = msg.send() if response == 1: messages.add_message(request, messages.INFO, booking.customer_email) return render(request, 'thank_you.html', {"center":center.name}) else : return render(request, template_name, {'form': form}) else: # Set error context error_msg = cls_default_msgs['not_signed_in'] messages.add_message(request, messages.INFO, error_msg, form.errors) # Set template template = Engine.get_default().get_template('login.html') # Set result in RequestContext context = RequestContext(request) return HttpResponse(template.render(context)) else: form = form_class(request.user, center) return render(request, template_name, { 'center': center, 'form': form, })
def render_template(self, name, context={}): """ Returns the rendered template with the provided name. """ engine = Engine.get_default() return engine.get_template(name).render(Context(context))
from django.template import Context from django.test import TestCase from guardian.shortcuts import assign_perm from feder.users.factories import UserFactory from django.core import mail from ..factories import IncomingLetterFactory from ..forms import ReplyForm try: from django.template.loader import get_template_from_string except ImportError: from django.template import Engine get_template_from_string = Engine.get_default().from_string def dict_merge(dict_a, *mergable): merged = dict_a.copy() [merged.update(x) for x in mergable] return merged class ReplyFormTestCase(TestCase): def setUp(self): self.user = UserFactory(username='******') self.letter = IncomingLetterFactory() def render_form(self, form): template = get_template_from_string("""
def engine(): """ Configura a engine de Templates do Django """ engine = Engine.get_default() return engine
import re from django.template import TemplateDoesNotExist, Context from django.template import Engine engine = Engine.get_default() find_template = engine.find_template find_template_loader = engine.find_template_loader get_template_from_string = engine.from_string select_template = engine.select_template make_origin = engine.make_origin from django.http import HttpResponse from django.conf import settings from tendenci.apps.theme.utils import get_theme_template, get_theme_root from tendenci.apps.site_settings.utils import get_setting non_theme_source_loaders = None def find_default_template(name, dirs=None): """ Exclude the theme.template_loader So we can properly get the templates not part of any theme. """ # Calculate template_source_loaders the first time the function is executed # because putting this logic in the module-level namespace may cause # circular import errors. See Django ticket #1292. global non_theme_source_loaders if non_theme_source_loaders is None: loaders = [] for loader_name in settings.TEMPLATE_LOADERS: if loader_name != 'theme.template_loaders.load_template_source':
def get_traceback_data(self): """Return a dictionary containing traceback information.""" try: default_template_engine = Engine.get_default() except Exception: # Since the debug view must never crash, catch all exceptions. # If Django can't find a default template engine, get_default() # raises ImproperlyConfigured. If some template engines fail to # load, any exception may be raised. default_template_engine = None # TODO: add support for multiple template engines (#24120). # TemplateDoesNotExist should carry all the information. # Replaying the search process isn't a good design. if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist): if default_template_engine is None: template_loaders = [] else: self.template_does_not_exist = True self.loader_debug_info = [] # If Django fails in get_template_loaders, provide an empty list # for the following loop to not fail. try: template_loaders = default_template_engine.template_loaders except Exception: template_loaders = [] for loader in template_loaders: try: source_list_func = loader.get_template_sources # NOTE: This assumes exc_value is the name of the template that # the loader attempted to load. template_list = [{ 'name': t, 'status': self.format_path_status(t), } for t in source_list_func(str(self.exc_value))] except AttributeError: template_list = [] loader_name = loader.__module__ + '.' + loader.__class__.__name__ self.loader_debug_info.append({ 'loader': loader_name, 'templates': template_list, }) frames = self.get_traceback_frames() for i, frame in enumerate(frames): if 'vars' in frame: frame_vars = [] for k, v in frame['vars']: v = pprint(v) # The force_escape filter assume unicode, make sure that works if isinstance(v, six.binary_type): v = v.decode('utf-8', 'replace') # don't choke on non-utf-8 input # Trim large blobs of data if len(v) > 4096: v = '%s... <trimmed %d bytes string>' % (v[0:4096], len(v)) frame_vars.append((k, force_escape(v))) frame['vars'] = frame_vars frames[i] = frame unicode_hint = '' if self.exc_type and issubclass(self.exc_type, UnicodeError): start = getattr(self.exc_value, 'start', None) end = getattr(self.exc_value, 'end', None) if start is not None and end is not None: unicode_str = self.exc_value.args[1] unicode_hint = smart_text( unicode_str[max(start - 5, 0):min(end + 5, len(unicode_str))], 'ascii', errors='replace' ) from django import get_version c = { 'is_email': self.is_email, 'unicode_hint': unicode_hint, 'frames': frames, 'request': self.request, 'filtered_POST': self.filter.get_post_parameters(self.request), 'settings': get_safe_settings(), 'sys_executable': sys.executable, 'sys_version_info': '%d.%d.%d' % sys.version_info[0:3], 'server_time': timezone.now(), 'django_version_info': get_version(), 'sys_path': sys.path, 'template_info': self.template_info, 'template_does_not_exist': self.template_does_not_exist, 'loader_debug_info': self.loader_debug_info, } # Check whether exception info is available if self.exc_type: c['exception_type'] = self.exc_type.__name__ if self.exc_value: c['exception_value'] = smart_text(self.exc_value, errors='replace') if frames: c['lastframe'] = frames[-1] return c
def makeEmail(self, recievers, context): if(type(recievers) is not list): recievers = [recievers] emails = [] for reciever in recievers: # each reciever must be Person, Family or string (email) # Note - string specifically removed. We use family.dont_send_mails to make sure # we dont send unwanted mails. if type(reciever) not in (members.models.person.Person, members.models.family.Family, members.models.department.Department): raise Exception("Reciever must be of type Person or Family not " + str(type(reciever))) # figure out reciever if(type(reciever) is str): # check if family blacklisted. (TODO) destination_address = reciever elif(type(reciever) is members.models.person.Person): # skip if family does not want email if reciever.family.dont_send_mails: continue context['person'] = reciever destination_address = reciever.email elif(type(reciever) is members.models.family.Family): # skip if family does not want email if reciever.dont_send_mails: continue context['family'] = reciever destination_address = reciever.email elif(type(reciever) is members.models.department.Department): context['department'] = reciever destination_address = reciever.responsible_contact # figure out Person and Family is applicable if(type(reciever) is members.models.person.Person): person = reciever elif('person' in context): person = context['person'] else: person = None # figure out family if(type(reciever) is members.models.family.Family): family = reciever elif(type(reciever) is members.models.person.Person): family = reciever.family elif('family' in context): family = context['family'] else: family = None # figure out activity if 'activity' in context: activity = context['activity'] else: activity = None # department if 'department' in context: department = context['department'] else: department = None # fill out known usefull stuff for context if 'email' not in context: context['email'] = destination_address if 'site' not in context: context['site'] = settings.BASE_URL if 'person' not in context: context['person'] = person if 'family' not in context: context['family'] = family # Make real context from dict context = Context(context) # render the template html_template = Engine.get_default().from_string(self.body_html) text_template = Engine.get_default().from_string(self.body_text) subject_template = Engine.get_default().from_string(self.subject) html_content = html_template.render(context) text_content = text_template.render(context) subject_content = subject_template.render(context) email = members.models.emailitem.EmailItem.objects.create(template=self, reciever=destination_address, person=person, family=family, activity=activity, department=department, subject=subject_content, body_html=html_content, body_text=text_content) email.save() emails.append(email) return emails