def render(self, context): for type in REGISTER_TYPES: if context_key(type) not in context: context[context_key(type)]=[] for arg in self.args: var = Variable(arg) try: value = var.resolve(context) except VariableDoesNotExist: raise TemplateSyntaxError('"static_add" tag got an unknkown variable: %r' % var.var) if isinstance(value, forms.BaseForm): for js in value.media._js: if_not_add(context, 'js', js) if "" in value.media._css: for css in value.media._css[""]: if_not_add(context, 'css', css) continue if callable(value): value=value() type = value[value.rfind('.')+1:].lower() assert type in REGISTER_TYPES, "Unknown compress_static type '%s'. Args: '%s'" % (type, self.args) if_not_add(context, type, value) return ""
class HasPermNode(Node): def __init__(self, user, perm, object=None, context_var=None): self.perm = perm self.context_var = context_var self.user = Variable(user) if object: self.object = Variable(object) else: self.object = object def render(self, context): if not self.user and not self.perm: return False has_perm = False user = self.user.resolve(context) if isinstance(user, User): # return true for admins if user.profile.is_superuser: has_perm = True else: if self.object: object = self.object.resolve(context) has_perm = utils.has_perm(user, self.perm, object) else: has_perm = utils.has_perm(user, self.perm) if self.context_var: context[self.context_var] = has_perm return '' else: return has_perm
def format_row(self, obj): row = [] for field in self.fields: if hasattr(obj, "get_{0}_display".format(field)): row.append(getattr(obj, "get_{0}_display".format(field))()) else: try: var = Variable("obj.{0}".format(field.replace("__", "."))) v = var.resolve({"obj": obj}) except VariableDoesNotExist: v = None if isinstance(v, bool): if v: row.append('<i class="fa fa-check text-success"></i>') else: row.append('<i class="fa fa-times text-danger"></i>') else: if hasattr(self, "link_column") and self.link_column == field: # NOTE: Added if statement and the first conditional code to make this work with linking project list to language detail. # The problems with the original one (under else) are: # 1. Charter model has 'lang_id' attribute that gets the related language's pk, but then the reverse() finds no match since # 'uw/language_detail/' looks for a "pk" as an argument, not a "lang_id". # 2. Charter model should not have more than one "pk" as attributes (one refers to itself, one refers to the related language's pk) # Solution: # 1. Rename the kwargs key to "pk" if the link_url_field is "lang_id" # NOTE by Vicky Leong, 10.12.15 if (self.link_url_field == "lang_id"): row.append('<a href="{0}">{1}</a>'.format(reverse(self.link_url_name, kwargs={"pk": getattr(obj, self.link_url_field)}), v)) else: row.append('<a href="{0}">{1}</a>'.format(reverse(self.link_url_name, kwargs={self.link_url_field: getattr(obj, self.link_url_field)}), v)) else: row.append(v) return row
class ExtendFilesNode(template.Node): def __init__(self, type, id, limit): self.type = Variable(type) self.id = Variable(id) self.limit = limit def render(self, context): try: id = self.id.resolve(context) type = self.type.resolve(context) except VariableDoesNotExist: id = None if type == 'Project': project = Project.objects.get(id = int(id)) if self.limit != None: context['files'] = project.link2project_set.all()[0:int(self.limit)] else: context['files'] = project.link2project_set.all() context['count'] = project.link2project_set.count() if type == 'Battery': battery = Battery.objects.get(id = int(id)) if self.limit != None: context['files'] = battery.link2battery_set.all()[0:int(self.limit)] else: context['files'] = battery.link2battery_set.all() context['count'] = battery.link2battery_set.count() return ''
class ProtocolCounterNode(Node): """ Class for protocol_counter template tag """ #---------------------------------------------------------------------- def __init__(self, model, team, release, varname): """Constructor""" self.model = get_model(*model.split('.')) self.varname = varname self.team = Variable(team) self.release = Variable(release) #---------------------------------------------------------------------- def render(self,context): """ Render the count from the asset model of choice """ try: team = self.team.resolve(context) release = self.release.resolve(context) context[self.varname] = self.model.active.filter(team__exact=team.id, release__exact=release.id).count() except template.VariableDoesNotExist: return '' return ''
def __init__(self, model, team, release, varname): """Constructor""" self.model = get_model(*model.split('.')) self.varname = varname self.team = Variable(team) self.release = Variable(release)
def __init__(self, src, version_prefix): self.src = Variable(src) if (version_prefix[0] == version_prefix[-1] and version_prefix[0] in ('"', "'")): self.version_prefix = version_prefix[1:-1] else: self.version_prefix = None self.version_prefix_var = Variable(version_prefix)
class VersionObjectNode(Node): def __init__(self, src, version_prefix, var_name): self.var_name = var_name self.src = Variable(src) if (version_prefix[0] == version_prefix[-1] and version_prefix[0] in ('"', "'")): self.version_prefix = version_prefix[1:-1] else: self.version_prefix = None self.version_prefix_var = Variable(version_prefix) def render(self, context): try: source = self.src.resolve(context) except VariableDoesNotExist: return None if self.version_prefix: version_prefix = self.version_prefix else: try: version_prefix = self.version_prefix_var.resolve(context) except VariableDoesNotExist: return None try: version_path = _get_version_path(_url_to_path(source), version_prefix) if not os.path.isfile(os.path.join(MEDIA_ROOT, version_path)): # create version version_path = _version_generator(_url_to_path(source), version_prefix) elif os.path.getmtime(os.path.join(MEDIA_ROOT, _url_to_path(source))) > os.path.getmtime(os.path.join(MEDIA_ROOT, version_path)): # recreate version if original image was updated version_path = _version_generator(_url_to_path(source), version_prefix, force=True) context[self.var_name] = FileObject(version_path) except: context[self.var_name] = "" return ''
def render(self, context): import feedparser cache_timeout = 300 if "cache" in self.kwargs: try: cache_timeout = Variable(self.kwargs["cache"]) cache_timeout = cache_timeout.resolve(context) except: cache_timeout = self.kwargs["cache"] cache_key = md5(self.url).hexdigest() url_content = cache.get(cache_key) if url_content is None: url_content = feedparser.parse(self.url) # We are going to try to pop out the errors in the # feed because they raise an exception that can't be # pickled when we try to cache the content. if "bozo_exception" in url_content: url_content["bozo_exception"] = "" cache.set(cache_key, url_content, int(cache_timeout)) context[self.context_var] = url_content return ""
class VersionNode(Node): def __init__(self, src, version_prefix): self.src = Variable(src) if (version_prefix[0] == version_prefix[-1] and version_prefix[0] in ('"', "'")): self.version_prefix = version_prefix[1:-1] else: self.version_prefix = None self.version_prefix_var = Variable(version_prefix) def render(self, context): try: source = self.src.resolve(context) except VariableDoesNotExist: return None if self.version_prefix: version_prefix = self.version_prefix else: try: version_prefix = self.version_prefix_var.resolve(context) except VariableDoesNotExist: return None try: source = force_unicode(source) version_path = get_version_path(url_to_path(source), version_prefix) if not os.path.isfile(smart_str(os.path.join(MEDIA_ROOT, version_path))): # create version version_path = version_generator(url_to_path(source), version_prefix) elif os.path.getmtime(smart_str(os.path.join(MEDIA_ROOT, url_to_path(source)))) > os.path.getmtime(smart_str(os.path.join(MEDIA_ROOT, version_path))): # recreate version if original image was updated version_path = version_generator(url_to_path(source), version_prefix, force=True) return path_to_url(version_path) except: return ""
class NearbyPages(Node): """ Takes a paginator and calculates the pages surrounding the current page number. Useful for creating rich content paginators. :param paginator: A paginator object from the Template context. :param page_num: The current page number (int) :param varname: An optional variable name to use when injecting the result into the Template context. """ def __init__(self, paginator, page_num, varname='nearby_pages'): self.paginator = Variable(paginator) self.page_num = Variable(page_num) self.varname = varname def render(self, context): paginator = self.paginator.resolve(context) page_num = self.page_num.resolve(context) nearby_pages = [n for n in range(page_num-2, page_num+3) \ if n > 0 and n <= paginator.num_pages] if len(nearby_pages) < 3: nearby_pages = None # Inject variable into template context context[self.varname] = nearby_pages return ''
class TagNode(Node): type = Variable('""') closed = Variable('""') def __init__(self, tag, nodelist, title, closed=False, type=None): self.tag = tag self.title = Variable(title) if type: self.type = Variable(type) if closed: self.closed = Variable(closed) self.nodelist = nodelist def render(self, context): inner = self.nodelist.render(context) t = loader.get_template('issues/core/%s.html' % self.tag) if self.closed: self.closed = self.closed.resolve(context) context = Context({ 'title': self.title.resolve(context), 'closed': self.closed, 'type': self.type.resolve(context), 'inner': inner, }) return t.render(context)
def render(self, context): user = AnonymousUser() if 'user' in context: if isinstance(context['user'], User): user = context['user'] try: pk = Variable(self.pk) pk = pk.resolve(context) except: pk = self.pk try: filters = get_query_filters(user, 'boxes.view_box') box = Box.objects.filter(filters).filter(pk=pk) if user.is_authenticated(): if not user.profile.is_superuser: box = box.distinct() context['box'] = box[0] template = get_template('boxes/edit-link.html') output = '<div id="box-%s" class="boxes">%s %s</div>' % ( box[0].pk, box[0].content, template.render(context), ) return output except: return unicode()
class IsFollowingListNode(Node): def __init__(self, var1, var2): self.var1 = Variable(var1) self.var2 = Variable(var2) def __repr__(self): return "<IsFollowingListNode>" def render(self, context): try: val1 = self.var1.resolve(context) except VariableDoesNotExist: val1 = None try: val2 = self.var2.resolve(context) except VariableDoesNotExist: val2 = None user_1 = get_object_or_404(User, id=val1) user_2 = get_object_or_404(User, id=val2) following_2 = isfollowing(user_1,user_2) if user_1!=user_2: if not following_2: html="<a href=\"/follow/"+user_2.username+"?to_do=follow\" id=\"follow\" > <span class=\"follow_icon\"><img src=\"/images/icons/plus.gif\" /></span> follow </a>" return html else: html="<span class=\"grey_bg\">you are already following</span>" return html else: return "yourself"
def __init__(self, day, type_slug, ordering, context_var): self.day = Variable(day) self.type_slug = Variable(type_slug) self.ordering = ordering if ordering: self.ordering = ordering.replace("'", '') self.context_var = context_var
def render(self, context): user = Variable('user').resolve(context) if not user.is_authenticated(): return self.nodelist_false.render(context) allowed = False for checkgroup in self.groups: if checkgroup.startswith('"') and checkgroup.endswith('"'): checkgroup = checkgroup[1:-1] if checkgroup.startswith("'") and checkgroup.endswith("'"): checkgroup = checkgroup[1:-1] try: group = Group.objects.get(name=checkgroup) except Group.DoesNotExist: try: group = Group.objects.get( name=Variable(checkgroup).resolve(context) ) except Group.DoesNotExist: group = None break if group in user.groups.all(): allowed = True break if allowed: return self.nodelist_true.render(context) else: return self.nodelist_false.render(context)
def render(self, context): user = Variable(self.user).resolve(context) post = Variable(self.post).resolve(context) if not user or not post: return '' context['show_post'] = post.is_visible_for_user(user) return ''
def render(self, context): file = self.file.resolve(context) if file and file.pk: cache_key = generate_image_cache_key(file=str(file.id), size=self.size, pre_key=FILE_IMAGE_PRE_KEY, crop=self.crop, unique_key=str(file.id), quality=self.quality, constrain=self.constrain) cached_image_url = cache.get(cache_key) if cached_image_url: return cached_image_url args = [file.pk] if self.size: try: size = Variable(self.size) size = size.resolve(context) except: size = self.size args.append(size) if self.crop: args.append("crop") if self.constrain: args.append("constrain") if self.quality: args.append(self.quality) url = reverse('file', args=args) return url # return the default image url return "%s%s" % (getattr(settings, 'STATIC_URL'), getattr(settings, 'DEFAULT_IMAGE_URL'))
def render(self, context): user = AnonymousUser() if 'user' in context: if isinstance(context['user'], User): user = context['user'] try: pk = Variable(self.pk) pk = pk.resolve(context) except: pk = self.pk try: filters = get_query_filters(user, 'navs.view_nav') nav = Nav.objects.filter(filters).filter(pk=pk) if user.is_authenticated(): if not user.profile.is_superuser: nav = nav.distinct() context[self.context_var] = nav[0] except: pass return unicode()
def navigation(context, nav_id): """ Renders the nav and its nav items. This will call nav_item that will call itself recursively nesting the subnavs """ user = AnonymousUser() if 'user' in context: if isinstance(context['user'], User): user = context['user'] try: nav_id = Variable(nav_id) nav_id = nav_id.resolve(context) except: pass try: filters = get_query_filters(user, 'navs.view_nav') navs = Nav.objects.filter(filters).filter(id=nav_id) if user.is_authenticated(): if not user.profile.is_superuser: navs = navs.distinct() nav = navs[0] except: return None context.update({ "nav": nav, "items": nav.top_items, }) return context
def render(self, context): try: collection = Variable(self.url).resolve(context) except VariableDoesNotExist: collection = None try: if not collection: collection = Collection.objects.get(url=self.url) object_list = collection.get_collection_objects()[:self.limit] result = [] for obj in object_list: try: obj = obj.content_object except AttributeError: pass app_label = obj._meta.app_label module_name = obj._meta.module_name context['object'] = obj t = template.loader.select_template(['news/collections/%s/%s_%s_%s.html' % (collection.id, app_label, module_name, obj.id), 'news/collections/%s/%s_%s.html' % (collection.id, app_label, module_name), 'news/collections/%s_%s.html' % (app_label, module_name)]) response = mark_safe(t.render(context)) result.append(response) context[self.varname] = result return '' except Exception, e: return "<!-- ERROR: %s -->" % e
def __init__(self, language, nodelist, name=''): self.language = Variable(language) self.nodelist = nodelist if name: self.name = Variable(name) else: self.name = None
def render(self, context): for arg in self.args: var = Variable(arg) try: value = var.resolve(context) except VariableDoesNotExist: raise TemplateSyntaxError('"compress" tag got an unknkown variable: %r' % var.var) if isinstance(value, forms.BaseForm): for js in value.media._js: add_to_compress(js) if "" in value.media._css: for css in value.media._css[""]: add_to_compress(css) if "all" in value.media._css: for css in value.media._css["all"]: add_to_compress(css) continue if callable(value): value=value() if isinstance(value, (types.ListType, types.TupleType)): for v in value: #print "ADDD:", v,"(",value,")" add_to_compress(v) else: add_to_compress(value) return ""
def __init__(self, amount, currency, *extra): self.amount = Variable(amount) self.currency = Variable(currency) if len(extra) >= 1: self.precision = int(extra[0]) else: self.precision = None
def render(self, context): print('render view tag...') if 'request' not in context: return "" request = context['request'] # get the url for the view url = Variable(self.url_or_view).resolve(context) if not settings.USE_AJAX_REQUESTS: # do not load the whole template, just the content, like an ajax request #request.is_ajax = True # not needed since the jQuery.get() is implying this urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) # get the view function view, args, kwargs = resolver.resolve(url) try: if callable(view): ret = view(context['request'], *args, **kwargs).render() return ret.rendered_content raise Exception("%r is not callable" % view) except: if settings.TEMPLATE_DEBUG: raise else: print('return js code for jquery') return """<div id="%(div_id)s">loading ...</div> <script> $.get( "%(url)s", function( data ) { $( "#%(div_id)s" ).html( data ); }); </script>""" % {'div_id': url.replace("/", ""), 'url': url} return ""
class PlayerCourseGraphNode(template.Node): def __init__(self, player, course): self.player = Variable(player) self.course = Variable(course) def render(self, context): super(PlayerCourseGraphNode, self).render(context) player = self.player.resolve(context) course = self.course.resolve(context) # Build a data structure for a players games data = { 'course': course.id, } results = [] for game in player.finishedgameplayer_set.filter( game__course=course).exclude(dnf=True).order_by('game__started'): results.append({ 'score': game.score, 'game': 'Game %i' % (game.game.id), }) data['results'] = results return json.dumps(data)
class CardNode(template.Node): def __init__(self, slug, text=None): self.slug = Variable(slug) self.text = Variable(text) if text else None def render(self, context): slug = self.slug.resolve(context) try: card = Card.objects.get(slug=slug) except Card.DoesNotExist: card = None text = "" if self.text: text = self.text.resolve(context) if not text and card: text = card.name if not text: text = "{card: %s}" % slug if card: url = card.get_absolute_url() else: url = "/admin/cards/card/add/?slug=%s" % slug title = "Learn more about %s" % text pos = int(context.get('pos', 0)) if card and card.died and pos > card.died: dead_class = ' dead' else: dead_class = '' text = text.replace(" ", " ") return "<a href='%s' class='cardlink%s' title='%s'>%s</a>" % (url, dead_class, title, text)
class VersionObjectNode(Node): def __init__(self, src, version_prefix, var_name): self.var_name = var_name self.src = Variable(src) if (version_prefix[0] == version_prefix[-1] and version_prefix[0] in ('"', "'")): self.version_prefix = version_prefix[1:-1] else: self.version_prefix = None self.version_prefix_var = Variable(version_prefix) def render(self, context): try: source = self.src.resolve(context) except VariableDoesNotExist: return None if self.version_prefix: version_prefix = self.version_prefix else: try: version_prefix = self.version_prefix_var.resolve(context) except VariableDoesNotExist: return None try: source = force_unicode(source) version_path = get_version_path(source, version_prefix) if not os.path.isfile(version_path): version_path = version_generator(source, version_prefix) elif os.path.getmtime(source) > os.path.getmtime(version_path): version_path = version_generator(source, version_prefix, force=True) context[self.var_name] = FileObject(version_path) except: context[self.var_name] = "" return ''
class MDCTNode(Node): def __init__(self,var_name,fmt_name=settings.DEFAULT_TIME_FORMAT, tz_var=None): self.var_name = Variable(var_name) if tz_var is None: self.tz_var = None else: self.tz_var = Variable(tz_var) self.fmt_name = fmt_name def render(self, context): tz_name = settings.DEFAULT_TZ if self.tz_var is None: user = Variable('user').resolve(context) if user.is_authenticated(): tz_name = user.get_profile().time_zone else: tz_name = self.tz_var.resolve(context) dt = self.var_name.resolve(context) utc = pytz.timezone('UTC') tz = pytz.timezone(tz_name) dt = utc.localize(dt) dt = dt.astimezone(tz) return dt.strftime(settings.TIME_FORMATS[self.fmt_name])
class FormatQuipQueryNode(Node): def __init__(self, var1, var2): self.var1 = Variable(var1) self.var2 = Variable(var2) def __repr__(self): return "<FormatQuipQueryNode>" def render(self, context): try: val1 = self.var1.resolve(context) except VariableDoesNotExist: val1 = None try: val2 = self.var2.resolve(context) except VariableDoesNotExist: val2 = None query = val1 text = val2 location = string.find(text.upper(),query.upper()) if location>40: cropped_text = text[location-40:location+40] text = "..."+cropped_text+"..." else: cropped_text = text[:location+40] text = cropped_text+"..." replacement = '<span class="highlighter">'+query+'</span>' data_object = ireplace(text,query,replacement) return data_object
def __init__(self, nodelist, expire_time_var, fragment_name, vary_on): self.nodelist = nodelist self.expire_time_var = Variable(expire_time_var) self.fragment_name = fragment_name self.vary_on = vary_on
def __init__(self, file, *args, **kwargs): self.size = kwargs.get("size", None) self.crop = kwargs.get("crop", False) self.quality = kwargs.get("quality", None) self.constrain = kwargs.get("constrain", None) self.file = Variable(file)
def __init__(self, actor): self.actor = Variable(actor)
def __init__(self, actor, actor_only=True): self.actor = Variable(actor) self.actor_only = actor_only
def resolve(self, context, request=None, current_path=None, current_view=None, resolved_object=None): # Don't calculate these if passed in an argument request = request or Variable('request').resolve(context) current_path = current_path or request.META['PATH_INFO'] current_view = current_view or resolve(current_path).url_name # Preserve unicode data in URL query previous_path = smart_unicode( urllib.unquote_plus( smart_str(request.get_full_path()) or smart_str(request.META.get('HTTP_REFERER', u'/')))) query_string = urlparse.urlparse(previous_path).query parsed_query_string = urlparse.parse_qs(query_string) logger.debug('condition: %s', self.condition) if resolved_object: context['resolved_object'] = resolved_object # Check to see if link has conditional display if self.condition: self.condition_result = self.condition(context) else: self.condition_result = True logger.debug('self.condition_result: %s', self.condition_result) if self.condition_result: resolved_link = ResolvedLink() resolved_link.text = self.text resolved_link.icon = self.icon resolved_link.permissions = self.permissions resolved_link.condition_result = self.condition_result try: #args, kwargs = resolve_arguments(context, self.get('args', {})) args, kwargs = Link.resolve_arguments(context, self.args) except VariableDoesNotExist: args = [] kwargs = {} if self.view: if not self.dont_mark_active: resolved_link.active = self.view == current_view try: if kwargs: resolved_link.url = reverse(self.view, kwargs=kwargs) else: resolved_link.url = reverse(self.view, args=args) if self.keep_query: resolved_link.url = u'%s?%s' % ( urlquote(resolved_link.url), urlencode(parsed_query_string, doseq=True)) except NoReverseMatch, exc: resolved_link.url = '#' resolved_link.error = exc elif self.url: if not self.dont_mark_active: resolved_link.url.active = self.url == current_path if kwargs: resolved_link.url = self.url % kwargs else: resolved_link.url = self.url % args if self.keep_query: resolved_link.url = u'%s?%s' % ( urlquote(resolved_link.url), urlencode(parsed_query_string, doseq=True)) else: resolved_link.active = False if self.conditional_highlight: resolved_link.active = self.conditional_highlight(context) if self.conditional_disable: resolved_link.disabled = self.conditional_disable(context) else: resolved_link.disabled = False if current_view in self.children_views: resolved_link.active = True # TODO: eliminate url_regexes and use new tree base main menu for children_view_regex in self.children_view_regex: if re.compile(children_view_regex).match(current_view): resolved_link.active = True return resolved_link
def get_context_navigation_links(cls, context, menu_name=None, links_dict=None): request = Variable('request').resolve(context) current_path = request.META['PATH_INFO'] current_view = resolve(current_path).url_name context_links = {} if not links_dict: links_dict = Link.bound_links if menu_name not in links_dict: return [] # Don't fudge with the original global dictionary # TODO: fix this links_dict = links_dict.copy() # Dynamic sources # TODO: improve name to 'injected...' # TODO: remove, only used by staging files try: """ Check for and inject a temporary navigation dictionary """ temp_navigation_links = Variable( 'temporary_navigation_links').resolve(context) if temp_navigation_links: links_dict.update(temp_navigation_links) except VariableDoesNotExist: pass # Get view only links try: view_links = links_dict[menu_name][current_view]['links'] except KeyError: pass else: context_links[None] = [] for link in view_links: context_links[None].append( link.resolve(context, request=request, current_path=current_path, current_view=current_view)) # Get object links for resolved_object in Link.get_navigation_objects(context).keys(): for source, data in links_dict[menu_name].items(): if inspect.isclass(source) and isinstance( resolved_object, source) or Combined( obj=type(resolved_object), view=current_view) == source: context_links[resolved_object] = [] for link in data['links']: context_links[resolved_object].append( link.resolve(context, request=request, current_path=current_path, current_view=current_view, resolved_object=resolved_object)) break # No need for further content object match testing return context_links
def __init__(self, paginator, page_number, context_var): self.paginator = Variable(paginator) self.page_number = Variable(page_number) self.context_var = context_var
def __init__(self, *args, **kwargs): self.bits = [Variable(bit) for bit in kwargs.get("bits", [])[1:]]
def __init__(self, title, url_node): self.title = Variable(title) self.url_node = url_node
def __init__(self, photo, *args, **kwargs): self.size = kwargs.get("size", "100x100") self.crop = kwargs.get("crop", False) self.constrain = kwargs.get("constrain", False) self.quality = kwargs.get("quality", 90) self.photo = Variable(photo)
def __init__(self, *args, **kwargs): self.args = [Variable(arg) for arg in args] self.kwargs = dict([(k, Variable(arg)) for k, arg in kwargs.items()])
def resolve(self, var, context): """Resolves a variable out of context if it's not in quotes""" if var[0] in ('"', "'") and var[-1] == var[0]: return var[1:-1] else: return Variable(var).resolve(context)
def __init__(self, string, start_string, nodelist_true, nodelist_false, negate): self.start_string, self.string = Variable(start_string), Variable(string) self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false self.negate = negate self.negate = negate
def render(self, context): tags = u'' query = u'' user = AnonymousUser() limit = 3 order = u'' randomize = False group = u'' if 'random' in self.kwargs: randomize = bool(self.kwargs['random']) if 'tags' in self.kwargs: try: tags = Variable(self.kwargs['tags']) tags = unicode(tags.resolve(context)) except: tags = self.kwargs['tags'] tags = tags.replace('"', '') tags = [t.strip() for t in tags.split(',')] if 'user' in self.kwargs: try: user = Variable(self.kwargs['user']) user = user.resolve(context) except: user = self.kwargs['user'] else: # check the context for an already existing user if 'user' in context: user = context['user'] if 'limit' in self.kwargs: try: limit = Variable(self.kwargs['limit']) limit = limit.resolve(context) except: limit = self.kwargs['limit'] limit = int(limit) if 'query' in self.kwargs: try: query = Variable(self.kwargs['query']) query = query.resolve(context) except: query = self.kwargs['query'] # context string if 'order' in self.kwargs: try: order = Variable(self.kwargs['order']) order = order.resolve(context) except: order = self.kwargs['order'] if 'group' in self.kwargs: try: group = Variable(self.kwargs['group']) group = unicode(group.resolve(context)) except: group = self.kwargs['group'] try: group = int(group) except: group = None filters = get_query_filters(user, self.perms) items = self.model.objects.filter(filters) if isinstance(user, User) and user.is_authenticated(): if not user.profile.is_superuser: items = items.distinct() if tags: # tags is a comma delimited list # this is fast; but has one hole # it finds words inside of other words # e.g. "prev" is within "prevent" tag_queries = [Q(tags__iexact=t.strip()) for t in tags] tag_queries += [Q(tags__istartswith=t.strip() + ",") for t in tags] tag_queries += [Q(tags__iendswith=", " + t.strip()) for t in tags] tag_queries += [Q(tags__iendswith="," + t.strip()) for t in tags] tag_queries += [ Q(tags__icontains=", " + t.strip() + ",") for t in tags ] tag_queries += [ Q(tags__icontains="," + t.strip() + ",") for t in tags ] tag_query = reduce(or_, tag_queries) items = items.filter(tag_query) if group: items = items.filter(group=group) objects = [] # Removed seconds and microseconds so we can cache the query better now = datetime.now().replace(second=0, microsecond=0) # Custom filter for stories date_query = reduce(or_, [Q(end_dt__gte=now), Q(expires=False)]) date_query = reduce(and_, [Q(start_dt__lte=now), date_query]) items = items.filter(date_query) if order: items = items.order_by(order) else: items = items.order_by('-position', '-start_dt') # if order is not specified it sorts by relevance if randomize: objects = [item for item in random.sample(items, len(items))][:limit] else: objects = [item for item in items[:limit]] context[self.context_var] = objects return ""
def parse_cvars(self, pairs): cvars = [] for vname, vobj in [pair.split("=") for pair in pairs]: cvars.append((vname, Variable(vobj))) return cvars
def __init__(self, request): self.request = Variable(request)
def resolve(self, var, context): return Variable(var).resolve(context)
def __init__(self, obj, var_name, with_feedback): self.obj = Variable(obj) self.var_name = var_name self.with_feedback = with_feedback
class AutoPaginateNode(Node): """ Emits the required objects to allow for Digg-style pagination. First, it looks in the current context for the variable specified, and using that object, it emits a simple ``Paginator`` and the current page object into the context names ``paginator`` and ``page_obj``, respectively. It will then replace the variable specified with only the objects for the current page. .. note:: It is recommended to use *{% paginate %}* after using the autopaginate tag. If you choose not to use *{% paginate %}*, make sure to display the list of available pages, or else the application may seem to be buggy. """ def __init__(self, queryset_var, multiple_paginations, paginate_by=None, orphans=None, context_var=None): if paginate_by is None: paginate_by = DEFAULT_PAGINATION if orphans is None: orphans = DEFAULT_ORPHANS self.queryset_var = Variable(queryset_var) if isinstance(paginate_by, int): self.paginate_by = paginate_by else: self.paginate_by = Variable(paginate_by) if isinstance(orphans, int): self.orphans = orphans else: self.orphans = Variable(orphans) self.context_var = context_var self.multiple_paginations = multiple_paginations def render(self, context): # Save multiple_paginations state in context if self.multiple_paginations and 'multiple_paginations' not in context: context['multiple_paginations'] = True if context.get('multiple_paginations') or getattr(context, "paginator", None): page_suffix = '_%s' % self.queryset_var else: page_suffix = '' key = self.queryset_var.var value = self.queryset_var.resolve(context) if isinstance(self.paginate_by, int): paginate_by = self.paginate_by else: paginate_by = self.paginate_by.resolve(context) if isinstance(self.orphans, int): orphans = self.orphans else: orphans = self.orphans.resolve(context) paginator = Paginator(value, paginate_by, orphans) try: request = context['request'] except KeyError: raise ImproperlyConfigured( "You need to enable 'django.core.context_processors.request'." " See linaro-django-pagination/README file for TEMPLATE_CONTEXT_PROCESSORS details") try: page_obj = paginator.page(request.page(page_suffix)) except InvalidPage: if INVALID_PAGE_RAISES_404: raise Http404('Invalid page requested. If DEBUG were set to ' + 'False, an HTTP 404 page would have been shown instead.') context[key] = [] context['invalid_page'] = True return '' if self.context_var is not None: context[self.context_var] = page_obj.object_list else: context[key] = page_obj.object_list context['paginator'] = paginator context['page_obj'] = page_obj context['page_suffix'] = page_suffix return ''
def resolve(self, var, context): if 'request' in context or 'user' in context: return Variable(var).resolve(context) return None
from django.conf import settings from django.db import models, connections from django.utils.translation import ugettext as _ from django.utils.http import urlquote from django.utils.encoding import iri_to_uri, force_text from django.utils.html import escape from django.utils.safestring import mark_safe from django.utils.text import capfirst from freppledb.common.models import User from freppledb import VERSION MAX_CRUMBS = 10 register = Library() variable_title = Variable("title") variable_request = Variable("request") variable_popup = Variable("is_popup") # # A tag to create breadcrumbs on your site # class CrumbsNode(Node): r''' A generic breadcrumbs framework. Usage in your templates: {% crumbs %}
def __init__(self, user, number, context_var): self.user = Variable(user) self.number = int(number) - 1 self.context_var = context_var
def __init__(self, languages, variable): self.languages = Variable(languages) self.variable = variable
def __init__(self, promotion): self.promotion_var = Variable(promotion)
def __init__(self, obj): self.obj = Variable(obj)
def __init__(self, filter_expression, noop): self.noop = noop self.filter_expression = filter_expression if isinstance(self.filter_expression.var, basestring): self.filter_expression.var = Variable(u"'%s'" % self.filter_expression.var)
def __init__(self, navnode, leaf_count, context_var): self.obj = Variable(navnode) self.leaf_count = int(leaf_count) self.context_var = context_var
def __init__(self, lang_code, variable): self.lang_code = Variable(lang_code) self.variable = variable
def __init__(self, species_name, context_var): self.obj = Variable(species_name) self.context_var = context_var
class GetCommentBoxPropsNode(Node): def __init__(self, obj): self.obj = Variable(obj) def render(self, context): obj = self.obj.resolve(context) form = CommentSecurityForm(obj) ctype = ContentType.objects.get_for_model(obj) queryset = XtdComment.objects.filter(content_type=ctype, object_pk=obj.pk, site__pk=settings.SITE_ID, is_public=True) ctype_slug = "%s-%s" % (ctype.app_label, ctype.model) d = { "comment_count": queryset.count(), "allow_comments": True, "current_user": "******", "request_name": False, "request_email_address": False, "is_authenticated": False, "allow_flagging": False, "allow_feedback": False, "show_feedback": False, "can_moderate": False, "poll_interval": 2000, "feedback_url": reverse("comments-xtd-api-feedback"), "delete_url": reverse("comments-delete", args=(0, )), "reply_url": reverse("comments-xtd-reply", kwargs={'cid': 0}), "flag_url": reverse("comments-flag", args=(0, )), "list_url": reverse('comments-xtd-api-list', kwargs={ 'content_type': ctype_slug, 'object_pk': obj.id }), "count_url": reverse('comments-xtd-api-count', kwargs={ 'content_type': ctype_slug, 'object_pk': obj.id }), "send_url": reverse("comments-xtd-api-create"), "form": { "content_type": form['content_type'].value(), "object_pk": form['object_pk'].value(), "timestamp": form['timestamp'].value(), "security_hash": form['security_hash'].value() } } user = context.get('user', None) try: user_is_authenticated = user.is_authenticated() except TypeError: # Django >= 1.11 user_is_authenticated = user.is_authenticated if user and user_is_authenticated: d['current_user'] = "******" % ( user.pk, settings.COMMENTS_XTD_API_USER_REPR(user)) d['is_authenticated'] = True d['can_moderate'] = user.has_perm("django_comments.can_moderate") d['request_name'] = True if not len( user.get_full_name()) else False d['request_email_address'] = True if not user.email else False else: d['login_url'] = "/admin/login/" d['like_url'] = reverse("comments-xtd-like", args=(0, )) d['dislike_url'] = reverse("comments-xtd-dislike", args=(0, )) return json.dumps(d)