def render(self, context): from django.db.models.options import Options from django.contrib.contenttypes.models import ContentType from freppledb.admin import data_site from django.core.urlresolvers import reverse try: # Look up the admin class to use model = Variable(self.model).resolve(context) if not model: return '' if isinstance(model, Options): ct = ContentType.objects.get(app_label=model.app_label, model=model.object_name.lower()) elif isinstance(model, models.Model): ct = ContentType.objects.get( app_label=model._meta.app_label, model=model._meta.object_name.lower()) else: model = model.split(".") ct = ContentType.objects.get(app_label=model[0], model=model[1]) admn = data_site._registry[ct.model_class()] if not hasattr(admn, 'tabs'): return '' # Render the admin class result = [ '<div class="row"><div id="tabs" class="col-md-12 form-inline hor-align-right"><ul class="nav nav-tabs">' ] obj = context['object_id'] active_tab = context.get('active_tab', 'edit') for tab in admn.tabs: if 'permissions' in tab: # A single permission is required if isinstance(tab['permissions'], str): if not context['request'].user.has_perm( tab['permissions']): continue else: # A list or tuple of permissions is given ok = True for p in tab['permissions']: if not context['request'].user.has_perm(p): ok = False break if not ok: continue # Append to the results result.append( '<li %srole="presentation"><a class="ui-tabs-anchor" href="%s%s" target="_self">%s</a></li>' % ('class="active" ' if active_tab == tab['name'] else '', context['request'].prefix, reverse(tab['view'], args=(obj, )), force_text(tab['label']).capitalize())) result.append('</ul></div></div>') return '\n'.join(result) except: if settings.TEMPLATE_DEBUG: raise return ''
def render(self, context): from django.db.models.options import Options from django.contrib.contenttypes.models import ContentType try: # Look up the admin class to use model = Variable(self.model).resolve(context) pk = Variable(self.pk).resolve(context) request = Variable("request").resolve(context) if not model or not pk: context[self.var] = None return mark_safe("") if isinstance(model, Options): ct = ContentType.objects.get(app_label=model.app_label, model=model.object_name.lower()) elif isinstance(model, models.Model): ct = ContentType.objects.get_for_model(model) else: model = model.split(".") ct = ContentType.objects.get(app_label=model[0], model=model[1]) context[self.var] = NotificationFactory.getFollower( object_pk=pk, content_type=ct, user=request.user, database=request.database, ) except Exception: context[self.var] = None return mark_safe("")
class MostPopularNode(Node): def __init__(self, appmodel, type, limit, days, varname, force=False): self.appmodel = appmodel self.limit = limit self.days = days self.varname = varname self.force = force if type == 'viewed': self.type = 'view_count' elif type == 'emailed': self.type = 'email_count' elif type == 'commented': self.type = 'comment_count' else: raise TemplateSyntaxError('The only supported types for this template tag are viewed, emailed, and commented.') def render(self, context): from courant.core.countthis.models import Statistic from datetime import timedelta, datetime try: self.appmodel = Variable(self.appmodel).resolve(context) except VariableDoesNotExist: pass #Just leave it alone #These are numbers, so either they'll resolve to a variable or resolve will return the number self.limit = Variable(self.limit).resolve(context) self.days = Variable(self.days).resolve(context) #We have to get the ContentType from the app.model string appmodel = self.appmodel.split('.') content_object = ContentType.objects.get(app_label=appmodel[0], model=appmodel[1]) content_object_model = content_object.model_class() content_type_list = [content_object.pk] for related_object in content_object_model._meta.get_all_related_objects(): if issubclass(related_object.model, content_object_model): content_type_list.append(ContentType.objects.get_for_model(related_object.model).pk) #Get the right objects while True: statistics_objects = Statistic.objects.filter(content_type__in=content_type_list, created_at__gte=datetime.now() - timedelta(days=self.days)).order_by('-' + self.type) #Do we have enough? if self.force and statistics_objects.count() < self.limit: self.days = self.days + 7 continue #We have enough! statistics_objects = statistics_objects[:self.limit] break #Create a dictionary of just the content_objects and view_counts, so they don't get Statistic models back and have to do object.content_object context[self.varname] = [{appmodel[1]: obj.content_object, 'count': getattr(obj, self.type)} for obj in statistics_objects] return ''
def render(self, context): from django.db.models.options import Options from django.contrib.contenttypes.models import ContentType from freppledb.admin import data_site from django.core.urlresolvers import reverse try: # Look up the admin class to use model = Variable(self.model).resolve(context) if isinstance(model, Options): ct = ContentType.objects.get(app_label=model.app_label, model=model.object_name.lower()) else: model = model.split(".") ct = ContentType.objects.get(app_label=model[0], model=model[1]) admn = data_site._registry[ct.model_class()] if not hasattr(admn, "tabs"): return "" # Render the admin class result = [ '<div class="row"><div id="tabs" class="col-md-12 form-inline hor-align-right"><ul class="nav nav-tabs">' ] obj = context["object_id"] active_tab = context.get("active_tab", "edit") for tab in admn.tabs: if "permissions" in tab: # A single permission is required if isinstance(tab["permissions"], str): if not context["request"].user.has_perm(tab["permissions"]): continue else: # A list or tuple of permissions is given ok = True for p in tab["permissions"]: if not context["request"].user.has_perm(p): ok = False break if not ok: continue # Append to the results result.append( '<li %srole="presentation"><a class="ui-tabs-anchor" href="%s%s">%s</a></li>' % ( 'class="active" ' if active_tab == tab["name"] else "", context["request"].prefix, reverse(tab["view"], args=(obj,)), force_text(tab["label"]).capitalize(), ) ) result.append("</ul></div></div>") return "\n".join(result) except: if settings.TEMPLATE_DEBUG: raise return ""
def render(self, context): from django.db.models.options import Options from django.contrib.contenttypes.models import ContentType from freppledb.admin import data_site from django.urls import reverse try: # Look up the admin class to use model = Variable(self.model).resolve(context) if not model: return mark_safe('') if isinstance(model, Options): ct = ContentType.objects.get(app_label=model.app_label, model=model.object_name.lower()) elif isinstance(model, models.Model): ct = ContentType.objects.get(app_label=model._meta.app_label, model=model._meta.object_name.lower()) else: model = model.split(".") ct = ContentType.objects.get(app_label=model[0], model=model[1]) admn = data_site._registry[ct.model_class()] if not hasattr(admn, 'tabs'): return mark_safe('') # Render the admin class result = ['<div class="row"><div id="tabs" class="col-md-12 form-inline hor-align-right"><ul class="nav nav-tabs">'] obj = context['object_id'] active_tab = context.get('active_tab', 'edit') for tab in admn.tabs: if 'permissions' in tab: # A single permission is required if isinstance(tab['permissions'], str): if not context['request'].user.has_perm(tab['permissions']): continue else: # A list or tuple of permissions is given ok = True for p in tab['permissions']: if not context['request'].user.has_perm(p): ok = False break if not ok: continue # Append to the results result.append( '<li %srole="presentation"><a class="ui-tabs-anchor" href="%s%s" target="_self">%s</a></li>' % ( 'class="active" ' if active_tab == tab['name'] else '', context['request'].prefix, reverse(tab['view'], args=(obj,)), force_text(tab['label']).capitalize() )) result.append('</ul></div></div>') return mark_safe('\n'.join(result)) except: raise
def render(self, context): tag_list_csv = Variable(self.tag_var).resolve(context) if (tag_list_csv is None): return None tag_list = tag_list_csv.split(',') #markup = "" #for tag in tag_list: # markup += '<a href="/blog-term/%s" name="blogtag">%s</a>' % (tag, tag) # what is the "has next" syntax in an iterator in python markup = ', '.join(['<a href="/alfresco/tag_search?q=%s" name="blogtag">%s</a>' % (tag, tag) for tag in tag_list]) return markup
def render(self, context): tag_list_csv = Variable(self.tag_var).resolve(context) if (tag_list_csv is None): return None tag_list = tag_list_csv.split(',') #markup = "" #for tag in tag_list: # markup += '<a href="/blog-term/%s" name="blogtag">%s</a>' % (tag, tag) # what is the "has next" syntax in an iterator in python markup = ', '.join([ '<a href="/alfresco/tag_search?q=%s" name="blogtag">%s</a>' % (tag, tag) for tag in tag_list ]) return markup
def render(self, context): tags = u'' query = u'' user = AnonymousUser() limit = 3 order = 'next_upcoming' event_type = '' group = u'' start_dt = u'' randomize = False if 'start_dt' in self.kwargs: try: start_dt = datetime.strptime(self.kwargs['start_dt'].replace('"', '').replace('"', ''), '%m/%d/%Y-%H:%M') except ValueError: pass 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 = tags.split(',') if 'user' in self.kwargs: try: user = Variable(self.kwargs['user']) user = user.resolve(context) except: user = self.kwargs['user'] if user == "anon" or user == "anonymous": user = AnonymousUser() else: # check the context for an already existing user # and see if it is really a user object if 'user' in context: if isinstance(context['user'], User): 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 'type' in self.kwargs: try: event_type = Variable(self.kwargs['type']) event_type = event_type.resolve(context) except: event_type = self.kwargs['type'] 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, 'events.view_event') items = Event.objects.filter(filters) if user.is_authenticated(): if not user.profile.is_superuser: items = items.distinct() if event_type: items = items.filter(type__name__iexact=event_type) 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 hasattr(self.model, 'group') and group: items = items.filter(groups=group) if hasattr(self.model, 'groups') and group: items = items.filter(groups__in=[group]) objects = [] if start_dt: items = items.filter(start_dt__gte=start_dt) # exclude private events items = items.filter(enable_private_slug=False) # if order is not specified it sorts by relevance if order: if order == "next_upcoming": if not start_dt: # Removed seconds and microseconds so we can cache the query better now = datetime.now().replace(second=0, microsecond=0) items = items.filter(start_dt__gt=now) items = items.order_by("start_dt") elif order == "current_and_upcoming": if not start_dt: now = datetime.now().replace(second=0, microsecond=0) items = items.filter(Q(start_dt__gt=now) | Q(end_dt__gt=now)) items = items.order_by("start_dt") elif order == "current_and_upcoming_by_hour": now = datetime.now().replace(second=0, microsecond=0) today = datetime.now().replace(second=0, hour=0, minute=0, microsecond=0) tomorrow = today + timedelta(days=1) items = items.filter(Q(start_dt__lte=tomorrow) & Q(end_dt__gte=today)).extra(select={'hour': 'extract( hour from start_dt )'}).extra(select={'minute': 'extract( minute from start_dt )'}).extra(where=["extract( hour from start_dt ) >= %s"], params=[now.hour]) items = items.distinct() items = items.order_by('hour', 'minute') else: items = items.order_by(order) if randomize: objects = [item for item in random.sample(items, items.count())][:limit] else: objects = [item for item in items[:limit]] context[self.context_var] = objects return ""
def render(self, context): from django.db.models.options import Options from django.contrib.contenttypes.models import ContentType from freppledb.admin import data_site from django.urls import reverse try: # Look up the admin class to use model = Variable(self.model).resolve(context) if not model: return mark_safe("") if isinstance(model, Options): ct = ContentType.objects.get(app_label=model.app_label, model=model.object_name.lower()) elif isinstance(model, models.Model): ct = ContentType.objects.get( app_label=model._meta.app_label, model=model._meta.object_name.lower(), ) else: model = model.split(".") ct = ContentType.objects.get(app_label=model[0], model=model[1]) admn = data_site._registry[ct.model_class()] if not hasattr(admn, "tabs"): return mark_safe("") # Render the admin class result = [ '<div class="row"><div id="tabs" class="col-md-12 form-inline hor-align-right"><ul class="nav nav-tabs">' ] obj = context["object_id"] active_tab = context.get("active_tab", "edit") for tab in admn.tabs: if "permissions" in tab: # A single permission is required if isinstance(tab["permissions"], str): if not context["request"].user.has_perm( tab["permissions"]): continue else: # A list or tuple of permissions is given ok = True for p in tab["permissions"]: if not context["request"].user.has_perm(p): ok = False break if not ok: continue # Append to the results result.append( '<li %srole="presentation"><a class="ui-tabs-anchor" href="%s%s?noautofilter" target="_self">%s</a></li>' % ( 'class="active" ' if active_tab == tab["name"] else "", context["request"].prefix, reverse(tab["view"], args=(obj, )), force_text(tab["label"]).capitalize(), )) result.append("</ul></div></div>") return mark_safe("\n".join(result)) except Exception: raise
def render(self, context): tags = u'' query = u'' user = AnonymousUser() limit = 3 order = u'' exclude = u'' randomize = False group = u'' status_detail = u'active' if 'random' in self.kwargs: randomize = bool(self.kwargs['random']) if 'tags' in self.kwargs: try: tags = Variable(self.kwargs['tags']) tags = str(tags.resolve(context)) except: tags = self.kwargs['tags'] tags = tags.replace('"', '') tags = tags.split(',') if 'user' in self.kwargs: try: user = Variable(self.kwargs['user']) user = user.resolve(context) except: user = self.kwargs['user'] if user == "anon" or user == "anonymous": user = AnonymousUser() # for performance reason, if user is not passed in, use AnonymousUser # else: # # check the context for an already existing user # # and see if it is really a user object # if 'user' in context: # if isinstance(context['user'], User): # 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 'exclude' in self.kwargs: try: exclude = Variable(self.kwargs['exclude']) exclude = str(exclude.resolve(context)) except: exclude = self.kwargs['exclude'] exclude = exclude.replace('"', '') exclude = exclude.split(',') if 'group' in self.kwargs: try: group = Variable(self.kwargs['group']) group = str(group.resolve(context)) except: group = self.kwargs['group'] try: group = int(group) except: group = None if 'status_detail' in self.kwargs: try: status_detail = Variable(self.kwargs['status_detail']) status_detail = status_detail.resolve(context) except: status_detail = self.kwargs['status_detail'] # get the list of items self.perms = getattr(self, 'perms', str()) # Only use the search index if there is a query passed if query: for tag in tags: tag = tag.strip() query = '%s "tag:%s"' % (query, tag) items = self.model.objects.search(user=user, query=query) else: filters = get_query_filters(user, self.perms) items = self.model.objects.filter(filters) if user.is_authenticated: 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 hasattr(self.model, 'group') and group: items = items.filter(group=group) if hasattr(self.model, 'groups') and group: items = items.filter(groups__in=[group]) if hasattr(self.model(), 'status_detail'): items = items.filter(status_detail__iexact=status_detail) items = self.custom_model_filter(items, user) objects = [] # exclude certain primary keys if exclude: excludes = [] for ex in exclude: if ex.isdigit(): excludes.append(int(ex)) if query: items = items.exclude(primary_key__in=excludes) else: items = items.exclude(pk__in=excludes) # if order is not specified it sorts by relevance if order: items = items.order_by(order) if randomize: items = list(items) objects = random.sample(items, min(len(items), limit)) else: objects = items[:limit] if query: objects = [item.object for item in objects] context[self.context_var] = objects if 'template' in self.kwargs: try: template = Variable(self.kwargs['template']) template = str(template.resolve(context)) except: template = self.kwargs['template'] t = context.template.engine.get_template(template) return t.render(context=context, autoescape=context.autoescape) return ""
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 = str(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 = str(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: items = list(items) objects = random.sample(items, min(len(items), limit)) else: objects = items[:limit] context[self.context_var] = objects return ""
def render(self, context): tags = u'' query = u'' user = AnonymousUser() limit = 3 order = 'next_upcoming' event_type = '' group = u'' start_dt = u'' randomize = False if 'start_dt' in self.kwargs: try: start_dt = datetime.strptime( self.kwargs['start_dt'].replace('"', '').replace('"', ''), '%m/%d/%Y-%H:%M') except ValueError: pass 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 = tags.split(',') if 'user' in self.kwargs: try: user = Variable(self.kwargs['user']) user = user.resolve(context) except: user = self.kwargs['user'] if user == "anon" or user == "anonymous": user = AnonymousUser() else: # check the context for an already existing user # and see if it is really a user object if 'user' in context: if isinstance(context['user'], User): 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 'type' in self.kwargs: try: event_type = Variable(self.kwargs['type']) event_type = event_type.resolve(context) except: event_type = self.kwargs['type'] 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, 'events.view_event') items = Event.objects.filter(filters) if user.is_authenticated(): if not user.profile.is_superuser: items = items.distinct() if event_type: items = items.filter(type__name__iexact=event_type) 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 hasattr(self.model, 'group') and group: items = items.filter(group=group) objects = [] if start_dt: items = items.filter(start_dt__gte=start_dt) # if order is not specified it sorts by relevance if order: if order == "next_upcoming": if not start_dt: # Removed seconds and microseconds so we can cache the query better now = datetime.now().replace(second=0, microsecond=0) items = items.filter(start_dt__gt=now) items = items.order_by("start_dt") elif order == "current_and_upcoming": if not start_dt: now = datetime.now().replace(second=0, microsecond=0) items = items.filter( Q(start_dt__gt=now) | Q(end_dt__gt=now)) items = items.order_by("start_dt") elif order == "current_and_upcoming_by_hour": now = datetime.now().replace(second=0, microsecond=0) today = datetime.now().replace(second=0, hour=0, minute=0, microsecond=0) tomorrow = today + timedelta(days=1) items = items.filter( Q(start_dt__lte=tomorrow) & Q(end_dt__gte=today)).extra( select={ 'hour': 'extract( hour from start_dt )' }).extra(select={ 'minute': 'extract( minute from start_dt )' }).extra(where=["extract( hour from start_dt ) >= %s"], params=[now.hour]) items = items.distinct() items = items.order_by('hour', 'minute') else: items = items.order_by(order) if randomize: objects = [item for item in random.sample(items, items.count())][:limit] else: objects = [item for item in items[:limit]] context[self.context_var] = objects return ""
def render(self, context): tags = u'' query = u'' user = AnonymousUser() limit = 3 order = u'' exclude = u'' randomize = False group = u'' status_detail = u'active' 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 = tags.split(',') if 'user' in self.kwargs: try: user = Variable(self.kwargs['user']) user = user.resolve(context) except: user = self.kwargs['user'] if user == "anon" or user == "anonymous": user = AnonymousUser() # for performance reason, if user is not passed in, use AnonymousUser # else: # # check the context for an already existing user # # and see if it is really a user object # if 'user' in context: # if isinstance(context['user'], User): # 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 'exclude' in self.kwargs: try: exclude = Variable(self.kwargs['exclude']) exclude = unicode(exclude.resolve(context)) except: exclude = self.kwargs['exclude'] exclude = exclude.replace('"', '') exclude = exclude.split(',') 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 if 'status_detail' in self.kwargs: try: status_detail = Variable(self.kwargs['status_detail']) status_detail = status_detail.resolve(context) except: status_detail = self.kwargs['status_detail'] # get the list of items self.perms = getattr(self, 'perms', unicode()) # Only use the search index if there is a query passed if query: for tag in tags: tag = tag.strip() query = '%s "tag:%s"' % (query, tag) items = self.model.objects.search(user=user, query=query) else: filters = get_query_filters(user, self.perms) items = self.model.objects.filter(filters) if user.is_authenticated(): 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 hasattr(self.model, 'group') and group: items = items.filter(group=group) if hasattr(self.model, 'groups') and group: items = items.filter(groups__in=[group]) if hasattr(self.model(), 'status_detail'): items = items.filter(status_detail__iexact=status_detail) items = self.custom_model_filter(items, user) objects = [] # exclude certain primary keys if exclude: excludes = [] for ex in exclude: if ex.isdigit(): excludes.append(int(ex)) if query: items = items.exclude(primary_key__in=excludes) else: items = items.exclude(pk__in=excludes) # if order is not specified it sorts by relevance if order: items = items.order_by(order) if randomize: objects = [item for item in random.sample(items, len(items))][:limit] else: objects = [item for item in items[:limit]] if query: objects = [item.object for item in objects] context[self.context_var] = objects if 'template' in self.kwargs: try: template = Variable(self.kwargs['template']) template = unicode(template.resolve(context)) except: template = self.kwargs['template'] t = loader.get_template(template) return t.render(Context(context, autoescape=context.autoescape)) return ""
def render(self, context): tags = u'' query = u'' user = AnonymousUser() limit = 3 order = 'next_upcoming' event_type = '' group = u'' randomize = False 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 = tags.split(',') if 'user' in self.kwargs: try: user = Variable(self.kwargs['user']) user = user.resolve(context) except: user = self.kwargs['user'] if user == "anon" or user == "anonymous": user = AnonymousUser() else: # check the context for an already existing user # and see if it is really a user object if 'user' in context: if isinstance(context['user'], User): 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 'type' in self.kwargs: try: event_type = Variable(self.kwargs['type']) event_type = event_type.resolve(context) except: event_type = self.kwargs['type'] 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, 'events.view_event') items = Event.objects.filter(filters) if user.is_authenticated(): if not user.profile.is_superuser: items = items.distinct() if event_type: items = items.filter(type__name__iexact=event_type) 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 hasattr(self.model, 'group') and group: items = items.filter(group=group) objects = [] # if order is not specified it sorts by relevance if order: if order == "next_upcoming": # Removed seconds and microseconds so we can cache the query better now = datetime.now().replace(second=0, microsecond=0) items = items.filter(start_dt__gt = now) items = items.order_by("start_dt") elif order == "current_and_upcoming": now = datetime.now().replace(second=0, microsecond=0) items = items.filter(Q(start_dt__gt=now) | Q(end_dt__gt=now)) items = items.order_by("start_dt") else: items = items.order_by(order) if randomize: objects = [item for item in random.sample(items, items.count())][:limit] else: objects = [item for item in items[:limit]] context[self.context_var] = objects return ""
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 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 render(self, context): tags = u'' query = u'' user = AnonymousUser() limit = 3 order = 'next_upcoming' event_type = '' randomize = False 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 = tags.split(',') if 'user' in self.kwargs: try: user = Variable(self.kwargs['user']) user = user.resolve(context) except: user = self.kwargs['user'] if user == "anon" or user == "anonymous": user = AnonymousUser() else: # check the context for an already existing user # and see if it is really a user object if 'user' in context: if isinstance(context['user'], User): 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 'type' in self.kwargs: try: event_type = Variable(self.kwargs['type']) event_type = event_type.resolve(context) except: event_type = self.kwargs['type'] # process tags for tag in tags: tag = tag.strip() query = '%s "tag:%s"' % (query, tag) filters = get_query_filters(user, 'events.view_event') items = Event.objects.filter(filters).distinct() if event_type: items = items.filter(type__name__iexact=event_type) objects = [] # if order is not specified it sorts by relevance if order: if order == "next_upcoming": # Removed seconds so we can cache the query better now = datetime.now().replace(second=0) items = items.filter(start_dt__gt = now) items = items.order_by("start_dt") else: items = items.order_by(order) if items: if randomize: objects = [item for item in random.sample(items, items.count())][:limit] else: objects = [item for item in items[:limit]] context[self.context_var] = objects return ""
def render(self, context): tags = u'' query = u'' user = AnonymousUser() limit = 3 order = u'' exclude = u'' randomize = False 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 = tags.split(',') if 'user' in self.kwargs: try: user = Variable(self.kwargs['user']) user = user.resolve(context) except: user = self.kwargs['user'] if user == "anon" or user == "anonymous": user = AnonymousUser() else: # check the context for an already existing user # and see if it is really a user object if 'user' in context: if isinstance(context['user'], User): 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 'exclude' in self.kwargs: try: exclude = Variable(self.kwargs['exclude']) exclude = unicode(tags.resolve(context)) except: exclude = self.kwargs['exclude'] exclude = exclude.replace('"', '') exclude = exclude.split(',') # get the list of items self.perms = getattr(self, 'perms', unicode()) filters = get_query_filters(user, self.perms) items = self.model.objects.filter(filters).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. "event" is within "prevent" tag_queries = [Q(tags__icontains=t) for t in tags] tag_query = reduce(or_, tag_queries) items = items.filter(tag_query) objects = [] if items: #exclude certain primary keys if exclude: excludes = [] for ex in exclude: if ex.isdigit(): excludes.append(int(ex)) items = items.exclude(pk__in=excludes) # if order is not specified it sorts by relevance if order: items = items.order_by(order) 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 if 'template' in self.kwargs: try: template = Variable(self.kwargs['template']) template = unicode(template.resolve(context)) except: template = self.kwargs['template'] t = loader.get_template(template) return t.render(Context(context, autoescape=context.autoescape)) return ""
def render(self, context): tags = u'' query = u'' user = AnonymousUser() limit = 3 order = 'next_upcoming' event_type = '' randomize = False 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 = tags.split(',') if 'user' in self.kwargs: try: user = Variable(self.kwargs['user']) user = user.resolve(context) except: user = self.kwargs['user'] if user == "anon" or user == "anonymous": user = AnonymousUser() else: # check the context for an already existing user # and see if it is really a user object if 'user' in context: if isinstance(context['user'], User): 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 'type' in self.kwargs: try: event_type = Variable(self.kwargs['type']) event_type = event_type.resolve(context) except: event_type = self.kwargs['type'] filters = get_query_filters(user, 'events.view_event') items = Event.objects.filter(filters) if user.is_authenticated(): if not user.profile.is_superuser: items = items.distinct() if event_type: items = items.filter(type__name__iexact=event_type) 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) objects = [] # if order is not specified it sorts by relevance if order: if order == "next_upcoming": # Removed seconds and microseconds so we can cache the query better now = datetime.now().replace(second=0, microsecond=0) items = items.filter(start_dt__gt=now) items = items.order_by("start_dt") elif order == "current_and_upcoming": now = datetime.now().replace(second=0, microsecond=0) items = items.filter(Q(start_dt__gt=now) | Q(end_dt__gt=now)) items = items.order_by("start_dt") else: items = items.order_by(order) if randomize: objects = [item for item in random.sample(items, items.count())][:limit] else: objects = [item for item in items[:limit]] context[self.context_var] = objects return ""