def get_related(self, max=10): """ Returns related entries based on related_content and similar tags """ related = self.related_content.all() if len(related) >= max: return related[:max] m = ModelTaggedItemManager() tag_related = m.related_to(self, queryset=Entry.objects.active(), num=max - len(related)) tag_related = [e for e in tag_related if not e in related] related_items = [] for e in related: related_items.append(e) for e in tag_related: related_items.append(e) return related_items[:max]
def register(model, tag_descriptor_attr='tags', tagged_item_manager_attr='tagged'): """ Sets the given model class up for working with tags. """ if model in registry: raise AlreadyRegistered("The model '%s' has already been registered." % model._meta.object_name) if hasattr(model, tag_descriptor_attr): raise AttributeError( "'%s' already has an attribute '%s'. You must provide a custom tag_descriptor_attr to register." % ( model._meta.object_name, tag_descriptor_attr, )) if hasattr(model, tagged_item_manager_attr): raise AttributeError( "'%s' already has an attribute '%s'. You must " "provide a custom tagged_item_manager_attr to register." % ( model._meta.object_name, tagged_item_manager_attr, )) # Add tag descriptor setattr(model, tag_descriptor_attr, TagDescriptor()) # Add custom manager ModelTaggedItemManager().contribute_to_class(model, tagged_item_manager_attr) # Finally register in registry registry.append(model)
def obj_get_list(self, bundle, **kwargs): user = bundle.request.user # by list list_id = kwargs.get('list_id') objects = super(BookmarkResource, self).obj_get_list(bundle, **kwargs) if list_id: l = List.objects.get(id=list_id) if user.has_perm('can_view', l) or user.has_perm( 'can_edit', l) or l.user == user: objects = Bookmark.objects.all() objects = objects.filter(list=l).order_by('-created_time') # by recent recent = bundle.request.GET.get('recent') if recent: objects = objects.order_by('-modified_time') # user feed feed = bundle.request.GET.get('feed') if feed: objects = Bookmark.objects.feed(user) # by tag tags = bundle.request.GET.get('tag') if tags: mtim = ModelTaggedItemManager() objects = mtim.with_all(tags, objects) q = bundle.request.GET.get('q') if q: try: UserApp.objects.get(user=user, app__key='search') sqs = SearchQuerySet().models(Bookmark).auto_query(q).filter( user_id=user.id) objects = objects.filter(pk__in=[i.pk for i in sqs]) except UserApp.DoesNotExist: objects = objects.filter( Q(title__icontains=q) | Q(tags__icontains=q) | Q(note__icontains=q)) return objects
def scrollable(context, tags=None, title=False, text=True, limit=5): """Displays objects with given tabs as scrollable """ items = lfc.utils.get_content_object(request) if tags: items = ModelTaggedItemManager().with_all(tags, items) return { "items": items, "title": title, "text": text, }
def items(self, obj): paths_objs = obj.get_descendants() tags = self.request.GET.getlist("tags") if not tags: return paths_objs else: objs = [] tagged_objs = ModelTaggedItemManager().with_all(tags, BaseContent.objects.all()) for obj in tagged_objs: if obj.get_content_object() in paths_objs: objs.append(obj.get_content_object()) return objs
def obj_get_list(self, bundle, **kwargs): user = bundle.request.user # by list list_id = kwargs.get('list_id') objects = super(BookmarkResource, self).obj_get_list(bundle, **kwargs) if list_id: l = List.objects.get(id=list_id) if user.has_perm('can_view', l) or user.has_perm('can_edit', l) or l.user == user: objects = Bookmark.objects.all() objects = objects.filter(list=l).order_by('-created_time') # by recent recent = bundle.request.GET.get('recent') if recent: objects = objects.order_by('-modified_time') # user feed feed = bundle.request.GET.get('feed') if feed: objects = Bookmark.objects.feed(user) # by tag tags = bundle.request.GET.get('tag') if tags: mtim = ModelTaggedItemManager() objects = mtim.with_all(tags, objects) q = bundle.request.GET.get('q') if q: try: UserApp.objects.get(user=user, app__key='search') sqs = SearchQuerySet().models(Bookmark).auto_query(q).filter(user_id=user.id) objects = objects.filter(pk__in=[i.pk for i in sqs]) except UserApp.DoesNotExist: objects = objects.filter(Q(title__icontains=q) | Q(tags__icontains=q) | Q(note__icontains=q)) return objects
def register(model, tag_descriptor_attr='tags', tagged_item_manager_attr='tagged'): """ Sets the given model class up for working with tags. """ if model in registry: raise AlreadyRegistered( _('The model %s has already been registered.') % model.__name__) registry.append(model) # Add tag descriptor setattr(model, tag_descriptor_attr, TagDescriptor()) # Add custom manager ModelTaggedItemManager().contribute_to_class(model, tagged_item_manager_attr)
class Parrot(models.Model): state = models.CharField(max_length=50) perch = models.ForeignKey(Perch, null=True) objects = models.Manager() tagged = ModelTagManager() tagged_items = ModelTaggedItemManager() tags = TagDescriptor() spam = TagDescriptor(namespace='spam') spam2 = TagDescriptor(namespace='spam') attrs = TagDescriptor(namespace='attr') def __unicode__(self): return self.state class Meta: ordering = ['state']
@staticmethod def find_events(time_from=None, time_until=None, tags=None): if tags is not None: query = Event.tagged.with_all(tags) else: query = Event.objects.all() if time_from is not None: query = query.filter(when__gte=time_from) if time_until is not None: query = query.filter(when__lte=time_until) result = list(query.order_by("when")) return result def as_dict(self): return dict( when=self.when, what=self.what, data=self.data, tags=self.tags, id=self.id, ) # We use this rather than tagging.register() so that tags can be exposed # in the admin UI ModelTaggedItemManager().contribute_to_class(Event, 'tagged')
class Post(models.Model): LIVE_STATUS = 1 SUBMITTED_STATUS = 2 DRAFT_STATUS = 3 STATUS_CHOICES = ( (LIVE_STATUS, 'Live'), (SUBMITTED_STATUS, 'Submitted'), (DRAFT_STATUS, 'Draft'), ) live = LivePostManager() objects = models.Manager() tags = ModelTagManager() tagged = ModelTaggedItemManager() feed = models.ForeignKey(Feed) status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS) title = models.CharField(max_length=250) body = HTMLField() summary = models.CharField(max_length=250) pub_date = models.DateTimeField(default=datetime.datetime.now) pub_date_year = models.DateField(editable=False) posted = models.DateTimeField(default=datetime.datetime.now, editable=False) slug = models.SlugField(unique_for_date='pub_date', blank=True, editable=False) topics = models.ManyToManyField(Topic, blank=True) cover = models.ForeignKey(Photo) gallery = models.ForeignKey(Gallery, blank=True, null=True, default=None) tags = TagField( help_text="Seperate with spaces. Put multi-word tags in quotes.", verbose_name='tags') featured = models.BooleanField(default=False) #Media media = models.FileField(upload_to=content_file_name, blank=True, null=True) #Podcast-specific info explicit = models.BooleanField(default=False) description = models.CharField(max_length=250, blank=True) mimetype = models.CharField(max_length=250, blank=True, editable=False) duration = models.CharField(max_length=250, blank=True, editable=False) block = models.BooleanField(default=False) class Meta: ordering = ['-pub_date'] permissions = (('can_publish_entry', 'Can publish entry'), ('can_publish_front', 'Can post on front page')) def save(self): self.pub_date_year = self.pub_date.date() self.slug = slugify(self.title) if len(self.slug) > 50: self.slug = self.slug[:49] if self.media: import mimetypes self.mimetype = mimetypes.guess_type(self.media.name) if 'audio' in self.mimetype: import audioread self.duration = int(audioread.audio_open(self.media.path).duration) elif ('video' in self.mimetype) and self.media: import subprocess process = subprocess.Popen( ['/usr/bin/ffmpeg', '-i', self.media.path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = process.communicate() matches = re.search( r"Duration:\s{1}(?P\d+?):(?P\d+?):(?P\d+\.\d+?),", stdout, re.DOTALL).groupdict() hours = Decimal(matches['hours']) minutes = Decimal(matches['minutes']) seconds = Decimal(matches['seconds']) total = 0 total += 60 * 60 * hours total += 60 * minutes total += seconds self.duration = total return super(Post, self).save() def __unicode__(self): return unicode(self.title) @models.permalink def get_absolute_url(self): return ('post_detail', (), { 'feed': self.feed.slug, 'year': self.pub_date.strftime("%Y"), 'month': self.pub_date.strftime("%b").lower(), 'day': self.pub_date.strftime("%d"), 'slug': self.slug })