class GetDataMarts(BaseRetrieveDataTag): name = 'get_data_marts' queryset = DataMartModel.objects.all() serializer_class = DataMartSummarySerializer action = 'list' filter_class = DataMartFilter filter_backends = (filters.SearchFilter, EDWFilterBackend, filters.OrderingFilter) ordering_fields = '__all__' pagination_class = DataMartPagination options = Options(MultiKeywordArgument('kwargs', required=False), 'as', Argument('varname', required=False, resolve=False)) def render_tag(self, context, kwargs, varname): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) data = self.get_paginated_data(serializer.data) context["{}_paginator".format(varname)] = self.paginator else: serializer = self.get_serializer(queryset, many=True) data = serializer.data if varname: context[varname] = data return '' else: return self.to_json(data)
class ActiveUrl(Tag, Configuration): '''django template tag via django-classy-tags''' # tag name name = 'activeurl' # template tag arguments options = Options( # all key based arguments mapped to one dict MultiKeywordArgument('kwargs', required=False), blocks=[('endactiveurl', 'nodelist')]) def render_tag(self, context, kwargs, nodelist): '''render content with "active" urls logic''' # load configuration from passed options self.load_configuration(kwargs) # get request from context request = context['request'] # get full path from request self.full_path = request.get_full_path() # render content of template tag context.push() content = nodelist.render(context) context.pop() # check content for "active" urls content = render_content(content, self.full_path, self.parent_tag, self.css_class, self.menu) return content
class PriceTag(Tag): name = 'price' options = Options( MultiKeywordArgument( 'kwargs', required=False ), 'as', Argument( 'varname', default='price', required=False, resolve=False ), blocks=[('endprice', 'nodelist')], ) # pylint:disable=arguments-differ def render_tag(self, context, kwargs, varname, nodelist): price = Price.calculate(**kwargs) context.push() context[varname] = price output = nodelist.render(context) context.pop() return output
class ShowMultiMenu(InclusionTag): DEFAULT_TEMPLATE_NAME = "multimenus/menu.html" name = 'show_multi_menu' push_context = True options = Options( Argument('menu_id', required=True), Argument('template', required=False), MultiKeywordArgument('params', required=False) ) def get_template(self, context, **kwargs): template_name = kwargs.get('template') if not template_name: template_name = ShowMultiMenu.DEFAULT_TEMPLATE_NAME return template_name def get_context(self, context, menu_id, template=None, params={}): current_site = get_current_site(context['request']) cache_key = get_cache_key(menu_id, current_site.pk, get_language()) menu_items = cache.get(cache_key) if menu_items is None: try: menu = MenuItem.objects.get(site=current_site, menu_id=menu_id) if 'include_self' in params and params['include_self']: menu_items = [menu, ] else: menu_items = menu.get_children() except MenuItem.DoesNotExist: menu_items = [] cache.set(cache_key, menu_items, 60 * 60 * 24) return { 'items': menu_items, 'template': template or ShowMultiMenu.DEFAULT_TEMPLATE_NAME, }
class VariationsTag(Tag): name = 'variations' options = Options( Argument('product'), MultiKeywordArgument('kwargs', required=False), blocks=[('endvariations', 'nodelist')], ) def render_tag(self, context, product, kwargs, nodelist): variations = None grouped = kwargs.pop('grouped', None) if variations is None: variations = product.get_variations() if grouped: variations = variations.group() elif grouped is None: # Try to get grouped variations # else return regular variations. grouped_variations = variations.group() if grouped_variations: grouped = True variations = grouped_variations context.push() context['variations'] = variations context['grouped'] = grouped output = nodelist.render(context) context.pop() return output
class InlineZenformTag(ZenformTag): name = 'izenform' options = Options( Argument('form'), 'options', MultiKeywordArgument('options', required=False, default=DEFAULT_OPTIONS), ) def render_tag(self, context, form, options): context.push() real_options = DEFAULT_OPTIONS.copy() real_options.update({'izenform': True}) real_options.update(options) context['form'] = self.prepare_form(form) context['fields'] = context['form'] context['options'] = real_options prefix = self.render_prefix(context) postfix = self.render_postfix(context) content = loader.get_template('zenforms/zenform_inline.html').render( context) output = prefix + content + postfix context.pop() return output
class AlterUrl(Tag): name = 'alter_url' options = Options( Argument('url', required=False), 'params', MultiKeywordArgument('params', required=False), 'remove', MultiValueArgument('remove', required=False), ) def render_tag(self, context, url, params, remove): if url is None: url = context['request'].get_full_path() url = yurl.URL(url) query = urllib.parse.parse_qs(url.query) for k in remove: query.pop(k, None) for k, v in params.items(): query[k] = [v] query = urllib.parse.urlencode(query, doseq=True) return str(url.replace(query=query))
class QueryParameters(Tag): name = 'query' options = Options(MultiKeywordArgument('kwa'), ) def render_tag(self, context, kwa): q = QueryDict('').copy() q.update(kwa) return q.urlencode()
class CMSAdminURL(AsTag): name = 'cms_admin_url' options = Options( Argument('viewname'), MultiValueArgumentBeforeKeywordArgument('args', required=False), MultiKeywordArgument('kwargs', required=False), 'as', Argument('varname', resolve=False, required=False)) def get_value(self, context, viewname, args, kwargs): return admin_reverse(viewname, args=args, kwargs=kwargs)
class BootstrapField(PushPopInclusionTag): name = 'bootstrap_field' template = 'bootstrap_toolkit/field.html' options = Options( Argument('field'), MultiKeywordArgument('kwargs') ) def get_context(self, context, field, kwargs): context.update(kwargs) context['field'] = field return context
class BootstrapFormset(PushPopInclusionTag): name = 'bootstrap_formset' template = 'bootstrap_toolkit/formset.html' options = Options( Argument('formset'), MultiKeywordArgument('kwargs') ) def get_context(self, context, formsset, kwargs): context.update(kwargs) context['formset'] = formset return context
class Rule(AsTag): options = Options( Argument('rule_name'), MultiValueArgument('args', required=False), MultiKeywordArgument('kwargs', required=False), 'as', Argument('varname', resolve=False, required=False), ) def get_value(self, context, rule_name, args, kwargs): return rules_light.run(context['request'].user, rule_name, *args, **kwargs)
class CellButtonRenderer(InclusionTag): template = 'includes/elements/cell_button.html' name = 'cell_button' options = Options( Argument('text'), MultiKeywordArgument('options', required=False), 'url', Argument('url_name'), MultiKeywordArgument('url_kwargs', required=False), ) def get_context(self, context, text, options, url_name, url_kwargs): icon = options.get('icon') return { 'text': text, 'show_text': not icon or options.get('show_text'), 'icon': icon, 'modal': options.get('modal'), 'url': reverse(url_name, kwargs=url_kwargs), }
class MenuItemsRenderer(Tag): name = 'children' options = Options( Argument('menu'), 'with', MultiKeywordArgument('kwargs', required=False), ) def render_tag(self, context, menu, kwargs): return '\n'.join( item.render(context['request'], kwargs=kwargs) for item in menu)
class Panel(BasePanel): name = 'panel' template = 'tags/panel.html' options = Options( Argument('title'), MultiKeywordArgument('kw', required=False), blocks=[('endpanel', 'nodelist')], ) def get_panel_context(self, arguments): kw = arguments.pop('kw') arguments['state'] = kw.get('state', 'default') arguments['icon'] = kw.get('icon', 'fa-cube') return arguments
class BaseChart(BasePanel): name = 'chart' template = 'tags/chart.html' options = Options( Argument('container_id'), MultiKeywordArgument('kw', required=False), blocks=[('endchart', 'nodelist')], ) DEFAULT_STYLES = 'min-width: 310px; height: 400px; margin: 0 auto' def get_panel_context(self, arguments): kw = arguments.pop('kw') arguments['style'] = kw.get('style', self.DEFAULT_STYLES) return arguments
class GetTermTree(BaseRetrieveDataTag): name = 'get_term_tree' queryset = TermModel.objects.toplevel() serializer_class = TermTreeSerializer action = 'tree' options = Options(MultiKeywordArgument('kwargs', required=False), 'as', Argument('varname', required=False, resolve=False)) def render_tag(self, context, kwargs, varname): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True, context=context) data = serializer.data if varname: context[varname] = data return '' else: return self.to_json(data)
class GetEntity(BaseRetrieveDataTag): name = 'get_entity' queryset = EntityModel.objects.all() serializer_class = EntityDetailSerializer action = 'retrieve' options = Options(Argument('pk', resolve=True), MultiKeywordArgument('kwargs', required=False), 'as', Argument('varname', required=False, resolve=False)) def render_tag(self, context, pk, kwargs, varname): instance = self.get_object() serializer = self.get_serializer(instance) data = serializer.data if varname: context[varname] = data return '' else: return self.to_json(data)
class PlaceWidget(InclusionTag): template = "widget/single_holder.html" name = 'place_widget' options = Options( Argument('slot', required=True, resolve=False), MultiKeywordArgument('kwargs', required=True, resolve=False), ) def get_context(self, context, slot, kwargs): page = context.get('page', None) context['slot'] = slot user = context['request'].user rendered = make_or_get_widget_for_slot(slot, context, **kwargs) if rendered: context['widget'] = rendered context['contains_widget'] = True else: context['contains_widget'] = False return context
class PlaceholderRT(Tag): name = 'placeholder_rt' options = Options( Argument('model_object', required=True), Argument('model_attribute', required=True, resolve=False), MultiKeywordArgument('kwords', required=False, resolve=True)) def render_tag(self, context, model_object, model_attribute, kwords): value = getattr(model_object, model_attribute) meta = escape( dumps({ 'app_label': model_object._meta.app_label, 'model_name': model_object.__class__.__name__, 'model_attribute': model_attribute, 'model_pk': model_object.pk })) params = {'tag': 'div', 'content': value, 'meta': meta} params.update(kwords) value = (u"<%(tag)s class=\"%(class)s\" data-placeholder-richtext " u"data-placeholder-meta=\"%(meta)s\">" u"%(content)s</%(tag)s>") % params return value
class SearchTag(BaseTwitterTag): name = 'search_tweets' options = Options( 'for', Argument('q'), 'as', Argument('asvar', resolve=False), MultiKeywordArgument('options', required=False), 'limit', Argument('limit', required=False), ) def get_cache_key(self, kwargs_dict): return get_search_cache_key(kwargs_dict) def get_api_call_params(self, **kwargs): params = {'q': kwargs['q'].encode('utf-8')} params.update(kwargs['options']) return params def get_json(self, twitter, **kwargs): return twitter.search.tweets(**kwargs)['statuses']
class GetDataMart(BaseRetrieveDataTag): name = 'get_data_mart' queryset = DataMartModel.objects.all() serializer_class = DataMartDetailSerializer action = 'retrieve' options = Options(Argument('pk', resolve=True), MultiKeywordArgument('kwargs', required=False), 'as', Argument('varname', required=False, resolve=False)) def render_tag(self, context, pk, kwargs, varname): instance = self.get_object() serializer = self.get_serializer(instance) data = serializer.data if varname: context[varname] = data return '' else: return self.to_json(data) def get_object(self): # try find object by `slug` # save origin lookups for monkey path origin_lookup_url_kwarg, origin_lookup_field = self.lookup_url_kwarg, self.lookup_field # Perform the lookup filtering. lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field # it was a string, not an int. try: int(self.initial_kwargs[lookup_url_kwarg]) except ValueError: self.lookup_url_kwarg, self.lookup_field = 'pk', 'slug' obj = super(GetDataMart, self).get_object() self.lookup_url_kwarg, self.lookup_field = origin_lookup_url_kwarg, origin_lookup_field return obj
class ShowMultiMenu(InclusionTag): DEFAULT_TEMPLATE_NAME = "multimenus/menu.html" name = "show_multi_menu" push_context = True options = Options( Argument("menu_id", required=True), Argument("template", required=False), MultiKeywordArgument("params", required=False), ) def get_template(self, context, **kwargs): template_name = kwargs.get("template") if not template_name: template_name = ShowMultiMenu.DEFAULT_TEMPLATE_NAME return template_name def get_context(self, context, menu_id, template=None, params={}): current_site = get_current_site(context["request"]) cache_key = "multimenus-{}-{}-{}".format(menu_id, current_site.pk, get_language()) menu_items = cache.get(cache_key) if menu_items is None: try: menu = MenuItem.objects.get(site=current_site, menu_id=menu_id) if "include_self" in params and params["include_self"]: menu_items = [ menu, ] else: menu_items = menu.get_children() except MenuItem.DoesNotExist: menu_items = [] cache.set(cache_key, menu_items, 60 * 60 * 24) return { "items": menu_items, "template": template or ShowMultiMenu.DEFAULT_TEMPLATE_NAME, }
class ZenformTag(Tag): """ Zenform tag is main application tag, it starts with ``{% zenform %}`` and ends with ``{% endzenform %}`` **Usage**:: {% zenform form [options key1=value1, key2=value2] %} Your form goes here! {% fieldset unused_fields title 'All my form' %} {% endzenform %} """ name = 'zenform' options = Options( Argument('form'), 'options', MultiKeywordArgument('options', required=False, default=DEFAULT_OPTIONS), blocks=[('endzenform', 'nodelist')], ) field_mapping = { forms.CharField: 'textInput', forms.EmailField: 'textInput', forms.IntegerField: 'textInput', forms.RegexField: 'textInput', forms.DateField: 'textInput', forms.DecimalField: 'textInput', forms.FloatField: 'textInput', } def prepare_form(self, form): for field in form: css_class = '' try: css_class = self.field_mapping[type(field.field)] except KeyError: pass if field.name in form.errors: css_class += ' error' if field.field.required: css_class += ' required' if 'class' in field.field.widget.attrs: field.field.widget.attrs['class'] += ' %s' % css_class else: field.field.widget.attrs['class'] = ' %s' % css_class return form def render_tag(self, context, form, options, nodelist): context.push() real_options = DEFAULT_OPTIONS.copy() real_options.update(options) context['form'] = self.prepare_form(form) context['options'] = real_options context['unused_fields'] = form.fields.keys() output = self.render_prefix(context) + nodelist.render( context) + self.render_postfix(context) context.pop() return output def render_prefix(self, context): template = loader.get_template('zenforms/zenform_prefix.html') return template.render(context) def render_postfix(self, context): template = loader.get_template('zenforms/zenform_postfix.html') return template.render(context)
class BaseRenderTemplateTag(Tag): """ RUS: Класс базового рендера шаблонных тегов. """ TEMPLATE_BUFFER_CACHE_KEY = 'tpl_bf' TEMPLATE_BUFFER_CACHE_SIZE = getattr(settings, 'TEMPLATE_BUFFER_CACHE_SIZE', 500) TEMPLATE_CACHE_KEY_PATTERN = 'tpl_i:{layout}:{alias_hash}:{terms_hash}' TEMPLATE_CACHE_TIMEOUT = getattr(settings, 'TEMPLATE_CACHE_TIMEOUT', 3600) template_queryset = EntityModel.objects.active() template_model = None options = Options(MultiKeywordArgument('kwargs', required=False), 'as', Argument('varname', required=False, resolve=False)) def get_template_queryset(self): """ Get the list of templates for this Tag. This must be an iterable, and may be a queryset. Defaults to using `self.queryset`. RUS: Получает список шаблонов для этого тега. """ assert self.template_model is not None, ( "'%s' should either include a `template_model` attribute, " "or override the `get_template_queryset()` method." % self.__class__.__name__) queryset = self.template_queryset if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() queryset = queryset.instance_of(self.template_model) return queryset def get_template(self, alias, layout=None, terms=None): """ Returns the template. RUS: Добавляет в термины id термина макета Возвращает шаблон. """ queryset = self.get_template_queryset().filter( **{ "{}___index__icontains".format(self.template_model._meta.object_name): alias }) # clear creation date, time terms & e.t. terms = list( TermModel.objects.filter(id__in=terms).exclude( system_flags=TermModel.system_flags. external_tagging_restriction).values_list( 'id', flat=True)) if terms is not None else [] if layout is not None: layout_term = get_views_layouts().get(layout, None) if layout_term is not None: terms.append(layout_term.id) return queryset.semantic_filter(terms, use_cached_decompress=True, fix_it=False).get_similar( terms, use_cached_decompress=True, fix_it=False) @staticmethod def get_template_buffer(): """ RUS: Собирает кольцевой буфер с ключом кэша и указанием максимального размера. """ return RingBuffer.factory( BaseRenderTemplateTag.TEMPLATE_BUFFER_CACHE_KEY, max_size=BaseRenderTemplateTag.TEMPLATE_BUFFER_CACHE_SIZE) @staticmethod def clear_template_buffer(): """ RUS: Очищает буфер, удаляя по указанным ключам. """ buf = BaseRenderTemplateTag.get_template_buffer() keys = buf.get_all() buf.clear() cache.delete_many(keys) def get_cached_template(self, alias, layout=None, terms=None): """ RUS: Возвращает шаблон с ключом кэша, если есть старый, - то он удаляется и перезаписывается. """ key = BaseRenderTemplateTag.TEMPLATE_CACHE_KEY_PATTERN.format( **{ "layout": layout if layout else '', "alias_hash": create_hash(':'.join( [self.template_model._meta.object_name, alias])), "terms_hash": hash_unsorted_list(terms) if terms else '' }) template = cache.get(key, empty) if template == empty: template = self.get_template(alias, layout, terms) cache.set(key, template, BaseRenderTemplateTag.TEMPLATE_CACHE_TIMEOUT) buf = BaseRenderTemplateTag.get_template_buffer() old_key = buf.record(key) if old_key != buf.empty: cache.delete(old_key) return template def render_tag(self, context, kwargs, varname): """ RUS: Отображает в шаблоне контекст, если есть шаблон. """ alias = kwargs.get('alias', 'index') template = self.get_cached_template( alias, kwargs.get('layout', PAGE_LAYOUT_ROOT_TERM_SLUG), kwargs.get('terms_ids')) if template is not None: sekizai_varname = sekizai_get_varname() ctx = copy.copy(context) request = ctx.get("request") ctx.update({ "params": kwargs, sekizai_varname: getattr(request, sekizai_varname) }) template_string = template.template.read_template(alias) t = django_template.Template(template_string) c = django_template.Context(ctx) data = t.render(c) else: data = '' if varname: context[varname] = data return '' else: return data
class GetEntities(BaseRetrieveDataTag): name = 'get_entities' queryset = EntityModel.objects.all() serializer_class = EntityTotalSummarySerializer action = 'list' filter_class = EntityFilter filter_backends = (EDWFilterBackend, EntityDynamicFilter, EntityMetaFilter, EntityGroupByFilter, EntityOrderingFilter) ordering_fields = '__all__' pagination_class = EntityPagination options = Options(MultiKeywordArgument('kwargs', required=False), 'as', Argument('varname', required=False, resolve=False)) def render_tag(self, context, kwargs, varname): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) data = self.get_paginated_data(serializer.data) pagination = { "limit": self.paginator.limit, "offset": self.paginator.offset, "next": self.paginator.get_next_link(), "previous": self.paginator.get_previous_link(), } data.update(pagination) context["{}_paginator".format(varname)] = self.paginator else: serializer = self.get_serializer(queryset, many=True) data = serializer.data if varname: context[varname] = data return '' else: return self.to_json(data) def get_serializer_context(self): context = super(GetEntities, self).get_serializer_context() context.update(self.queryset_context) return context def filter_queryset(self, queryset): queryset = super(GetEntities, self).filter_queryset(queryset) query_params = self.request.GET data_mart = query_params['_data_mart'] if data_mart is not None: query_params.setdefault( self.paginator.limit_query_param, str(data_mart.limit if data_mart.limit is not None else edw_settings.REST_PAGINATION['entity_default_limit'])) self.queryset_context = {"data_mart": data_mart, "extra": None} self.queryset_context.update({ key: query_params['_{}'.format(key)] for key in ("initial_filter_meta", "initial_queryset", "terms_filter_meta", "terms_ids", "subj_ids", "ordering", "view_component", "annotation_meta", "aggregation_meta", "group_by", "alike", "filter_queryset") }) return queryset