def tag_model( cls, admin_cls=None, field_name="tags", sort_tags=False, select_field=False, auto_add_admin_field=True, admin_list_display=True, ): """ tag_model accepts a number of named parameters: admin_cls If set to a subclass of ModelAdmin, will insert the tag field into the list_display and list_filter fields. field_name Defaults to "tags", can be used to name your tag field differently. sort_tags Boolean, defaults to False. If set to True, a pre_save handler will be inserted to sort the tag field alphabetically. This is useful in case you want a canonical representation for a tag collection, as when yo're presenting a list of tag combinations (e.g. in an admin filter list). select_field If True, show a multi select instead of the standard CharField for tag entry. auto_add_admin_field If True, attempts to add the tag field to the admin class. """ try: from tagging.registry import register as tagging_register except ImportError: from tagging import register as tagging_register cls.add_to_class( field_name, (TagSelectField if select_field else TagField)(field_name.capitalize(), blank=True), ) # use another name for the tag descriptor # See http://code.google.com/p/django-tagging/issues/detail?id=95 for the # reason why try: tagging_register(cls, tag_descriptor_attr="tagging_" + field_name) except AlreadyRegistered: return if admin_cls: if admin_list_display: admin_cls.list_display.append(field_name) admin_cls.list_filter.append(field_name) if auto_add_admin_field and hasattr(admin_cls, "add_extension_options"): admin_cls.add_extension_options(_("Tagging"), {"fields": (field_name, )}) if sort_tags: pre_save.connect(pre_save_handler, sender=cls)
def tag_model( cls, admin_cls=None, field_name="tags", sort_tags=False, select_field=False, auto_add_admin_field=True, admin_list_display=True, ): """ tag_model accepts a number of named parameters: admin_cls If set to a subclass of ModelAdmin, will insert the tag field into the list_display and list_filter fields. field_name Defaults to "tags", can be used to name your tag field differently. sort_tags Boolean, defaults to False. If set to True, a pre_save handler will be inserted to sort the tag field alphabetically. This is useful in case you want a canonical representation for a tag collection, as when yo're presenting a list of tag combinations (e.g. in an admin filter list). select_field If True, show a multi select instead of the standard CharField for tag entry. auto_add_admin_field If True, attempts to add the tag field to the admin class. """ try: from tagging.registry import register as tagging_register except ImportError: from tagging import register as tagging_register cls.add_to_class( field_name, (TagSelectField if select_field else TagField)( field_name.capitalize(), blank=True ), ) # use another name for the tag descriptor # See http://code.google.com/p/django-tagging/issues/detail?id=95 for the # reason why try: tagging_register(cls, tag_descriptor_attr="tagging_" + field_name) except AlreadyRegistered: return if admin_cls: if admin_list_display: admin_cls.list_display.append(field_name) admin_cls.list_filter.append(field_name) if auto_add_admin_field and hasattr(admin_cls, "add_extension_options"): admin_cls.add_extension_options(_("Tagging"), {"fields": (field_name,)}) if sort_tags: pre_save.connect(pre_save_handler, sender=cls)
blank=True, related_name="element_types") class Meta: ordering = ["name"] verbose_name_plural = "element types" # tagging_register adds a "tagged" manager that is considered as the default # manager, which is incompatible with polymorphic. So we explicitly set # the default manager default_manager_name = "objects" def __str__(self): return self.name tagging_register(ElementType) class MapElementType(ElementType): shape_ctype = models.ForeignKey( ContentType, on_delete=models.PROTECT, related_name="+", verbose_name="shape type", validators=[validate_shape_ctype], limit_choices_to=limit_shape_ctype, ) class Meta(ElementType.Meta): verbose_name_plural = "map element types"
"scours the instance data for useful tags" tags = set() keys = [["classification_description"], ["preparer"], ["introducer"], ["issue", "category_name"], ["meeting", "policymaker_name"]] for key in keys: value = self.original try: for part in key: value = value[part] if value is not None: tags.add("#" + slugify(value)[:49]) except KeyError: continue for t in tags: Tag.objects.add_tag(self, t) return self.tags def tag_cloud(self): "Returns instance tags annotated with tag cloud weights" # Just using self.tags doesn't aggregate properly (the only # matching item is self) tags = (Tag.objects.filter(pk__in=[t.pk for t in self.tags]).annotate( count=Count('items'))) return calculate_cloud(tags) tagging_register(AgendaItem)
qs = instance.release_albumartist_release.all() to_keep = [] to_delete = [] for aa in qs: t = (aa.join_phrase, aa.artist) if not t in to_keep: to_keep.append(t) else: to_delete.append(aa.pk) if to_delete: qs.filter(pk__in=to_delete).delete() try: tagging_register(Release) except Exception as e: pass arating.enable_voting_on(Release) class ReleaseExtraartists(models.Model): artist = models.ForeignKey('alibrary.Artist', related_name='release_extraartist_artist') release = models.ForeignKey('Release', related_name='release_extraartist_release') profession = models.ForeignKey(Profession, verbose_name='Role/Profession', related_name='release_extraartist_profession', blank=True, null=True) class Meta: app_label = 'alibrary' verbose_name = _('Role') verbose_name_plural = _('Roles')
parent = parent.parent if parent: last_parent = parent return last_parent def save(self, *args, **kwargs): unique_slugify(self, self.name) super(Label, self).save(*args, **kwargs) tagging_register(Label) arating.enable_voting_on(Label) # @receiver(post_save, sender=Label, dispatch_uid="label_post_save") # def action_handler_task(sender, instance, created, **kwargs): # # if created and instance.creator: # action.send(instance.creator, verb=_('created'), target=instance) # # elif instance.last_editor: # action.send(instance.last_editor, verb=_('updated'), target=instance) # def action_handler(sender, instance, created, **kwargs): # action_handler_task.delay(instance, created)
'pk': self.pk }) + '' def get_root(self): if not self.parent: return None if self.parent == self: return None parent = self.parent last_parent = None i = 0 while parent and i < 10: i += 1 parent = parent.parent if parent: last_parent = parent return last_parent def save(self, *args, **kwargs): unique_slugify(self, self.name) super(Label, self).save(*args, **kwargs) tagging_register(Label) arating.enable_voting_on(Label)
for t in tags: Tag.objects.add_tag(self, t) return self.tags def tag_cloud(self): "Returns instance tags annotated with tag cloud weights" # Just using self.tags doesn't aggregate properly (the only # matching item is self) tags = (Tag.objects .filter(pk__in=[t.pk for t in self.tags]) .annotate(count=Count('items'))) return calculate_cloud(tags) tagging_register(AgendaItem) class Comment(models.Model): user = models.ForeignKey(User, null=True) agendaitem = models.ForeignKey(AgendaItem) selector = models.CharField( max_length=200, help_text=_("This is the element where the comment " "attaches on a decision") ) quote = models.TextField( verbose_name=_("Quote"), help_text=_("Quotes are required.") ) text = models.TextField(
""" self.broadcast_status, self.broadcast_status_messages = self.self_check() # print '%s - %s (id: %s)' % (self.broadcast_status, self.name, self.pk) # print ', '.join(self.broadcast_status_messages) # map to object status (not extremly dry - we know...) if self.broadcast_status == 1: self.status = 1 # 'ready' else: self.status = 99 # 'error' # self.user = request.user super(Playlist, self).save(*args, **kwargs) try: tagging_register(Playlist) except Exception as e: pass arating.enable_voting_on(Playlist) @receiver(post_save, sender=Playlist) def playlist_post_save(sender, instance, **kwargs): if not instance.type == 'broadcast': return if instance.mixdown_file: return
obj = kwargs['instance'] # delete associated master file if obj.master and os.path.isfile(obj.master.path): os.unlink(obj.master.path) # delete fingerprint delete_fprint_for_media.apply_async((obj, )) pre_delete.connect(media_pre_delete, sender=Media) arating.enable_voting_on(Media) try: tagging_register(Media) except Exception as e: pass class MediaExtraartists(models.Model): artist = models.ForeignKey('alibrary.Artist', related_name='extraartist_artist', blank=True, null=True, on_delete=models.CASCADE) media = models.ForeignKey('Media', related_name='extraartist_media', blank=True, null=True,
self.duration = duration # TODO: maybe move self.broadcast_status, self.broadcast_status_messages = self.self_check( ) if self.broadcast_status == 1: self.status = 1 # 'ready' else: self.status = 99 # 'error' super(Playlist, self).save(*args, **kwargs) try: tagging_register(Playlist) except Exception as e: pass arating.enable_voting_on(Playlist) @receiver(post_save, sender=Playlist) def playlist_post_save(sender, instance, **kwargs): if not instance.type == 'broadcast': return if instance.mixdown_file: return
qs = instance.release_albumartist_release.all() to_keep = [] to_delete = [] for aa in qs: t = (aa.join_phrase, aa.artist) if not t in to_keep: to_keep.append(t) else: to_delete.append(aa.pk) if to_delete: qs.filter(pk__in=to_delete).delete() try: tagging_register(Release) except Exception as e: pass arating.enable_voting_on(Release) class ReleaseExtraartists(models.Model): artist = models.ForeignKey('alibrary.Artist', related_name='release_extraartist_artist') release = models.ForeignKey('Release', related_name='release_extraartist_release') profession = models.ForeignKey( Profession, verbose_name='Role/Profession', related_name='release_extraartist_profession',
in the case we - for whatever unplanned reason - there is a duplicate coming in we add a counter to the name ensure uniqueness. """ if self.name == 'Various Artists' and self.pk is None: log.warning('attempt to create "Various Artists"') original_name = self.name i = 1 while Artist.objects.filter(name=self.name).count() > 0: self.name = u'%s %s' % (original_name, i) i += 1 super(Artist, self).save(*args, **kwargs) tagging_register(Artist) arating.enable_voting_on(Artist) # @receiver(post_save, sender=Artist) # def action_handler(sender, instance, created, **kwargs): # try: # action_handler_task.delay(instance, created) # except: # pass # # @task # def action_handler_task(instance, created): # if created and instance.creator: # action.send(instance.creator, verb=_('created'), target=instance) # # elif instance.last_editor:
def get_api_url(self): return None # return reverse('api_dispatch_detail', kwargs={ # 'api_name': 'v1', # 'resource_name': 'profile', # 'pk': self.pk # }) def get_groups(self): return self.user.groups def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) try: tagging_register(Profile) except: pass arating.enable_voting_on(Profile) class Community(UUIDModelMixin, MigrationMixin): # uuid = UUIDField(primary_key=False) name = models.CharField(max_length=200, db_index=True) slug = AutoSlugField(populate_from='name', editable=True, blank=True, overwrite=True) group = models.OneToOneField(Group, unique=True, null=True, blank=True) members = models.ManyToManyField(User, blank=True)
return None # return reverse('api_dispatch_detail', kwargs={ # 'api_name': 'v1', # 'resource_name': 'profile', # 'pk': self.pk # }) def get_groups(self): return self.user.groups def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) try: tagging_register(Profile) except: pass arating.enable_voting_on(Profile) class Community(UUIDModelMixin, MigrationMixin): name = models.CharField(max_length=200, db_index=True) slug = AutoSlugField(populate_from='name', editable=True, blank=True, overwrite=True) group = models.OneToOneField(Group, unique=True, null=True, blank=True)
def save(self, *args, **kwargs): unique_slugify(self, self.name) t_tags = '' for tag in self.tags: t_tags += '%s, ' % tag self.tags = t_tags self.d_tags = t_tags super(Distributor, self).save(*args, **kwargs) try: tagging_register(Distributor) except Exception as e: pass class DistributorLabel(models.Model): distributor = models.ForeignKey('Distributor') label = models.ForeignKey('Label') exclusive = models.BooleanField(default=False) countries = models.ManyToManyField(Country, related_name="distribution_countries") class Meta: app_label = 'alibrary' verbose_name = _('Labels in catalog')
add a counter to the name ensure uniqueness. """ if self.name == 'Various Artists' and self.pk is None: log.warning('attempt to create "Various Artists"') original_name = self.name i = 1 while Artist.objects.filter(name=self.name).count() > 0: self.name = u'%s %s' % (original_name, i) i += 1 super(Artist, self).save(*args, **kwargs) tagging_register(Artist) arating.enable_voting_on(Artist) # @receiver(post_save, sender=Artist) # def action_handler(sender, instance, created, **kwargs): # try: # action_handler_task.delay(instance, created) # except: # pass # # @task # def action_handler_task(instance, created): # if created and instance.creator: # action.send(instance.creator, verb=_('created'), target=instance) # # elif instance.last_editor:
def save(self, *args, **kwargs): unique_slugify(self, self.name) t_tags = '' for tag in self.tags: t_tags += '%s, ' % tag self.tags = t_tags self.d_tags = t_tags super(Distributor, self).save(*args, **kwargs) try: tagging_register(Distributor) except Exception as e: pass class DistributorLabel(models.Model): distributor = models.ForeignKey( 'Distributor' ) label = models.ForeignKey( 'Label' ) exclusive = models.BooleanField( default=False )
# delete associated master file if obj.master and os.path.isfile(obj.master.path): os.unlink(obj.master.path) # delete fingerprint delete_fprint_for_media.apply_async((obj.uuid,)) pre_delete.connect(media_pre_delete, sender=Media) arating.enable_voting_on(Media) try: tagging_register(Media) except Exception as e: pass class MediaExtraartists(models.Model): artist = models.ForeignKey( 'alibrary.Artist', related_name='extraartist_artist', blank=True, null=True, on_delete=models.CASCADE ) media = models.ForeignKey( 'Media', related_name='extraartist_media', blank=True, null=True, on_delete=models.CASCADE
class MorphologyDefinition(models.Model): """Tells something about morphology of a gloss""" parent_gloss = models.ForeignKey(Gloss, related_name="parent_glosses") # role = models.CharField(max_length=5, choices=(build_choice_list('MorphologyType'))) role = models.ForeignKey('FieldChoice', to_field='machine_value', db_column='MorphologyType', limit_choices_to={'field': 'MorphologyType'}, blank=True) morpheme = models.ForeignKey(Gloss, related_name="morphemes") class Meta: verbose_name = _('Morphology definition') verbose_name_plural = _('Morphology definitions') def __str__(self): return str(self.morpheme.idgloss) + ' is ' + str( self.role) + ' of ' + str(self.parent_gloss.idgloss) # Register Models for django-tagging to add wrappers around django-tagging API. models_to_register_for_tagging = ( Gloss, GlossRelation, ) for model in models_to_register_for_tagging: try: tagging_register(model) except AlreadyRegistered: pass
def __unicode__(self): return "%s %s" % (self.code, self.heading) class Meta: ordering = ['id'] class hscode(models.Model): hs = models.CharField(max_length=20, verbose_name="HS-CODE") desc = models.TextField(verbose_name="HSCODE description") article = models.ForeignKey(Article) wef = models.DateField(auto_now=True, verbose_name='W.E.F', blank=True) policy = models.CharField(max_length=30, verbose_name="Policy Restriction") hs_5 = models.CharField(max_length=800, blank=True) hs_6 = models.CharField(max_length=800, blank=True) hs_8 = models.CharField(max_length=1000, blank=True) condition = models.CharField(max_length=1000, blank=True) note = models.ManyToManyField(Note, blank=True) class Meta: ordering = ['id'] def __unicode__(self): return self.hs tagging_register(hscode)
is_risky = models.BooleanField(default=False) objects = ElementManager() class Meta: ordering = ["name"] def __str__(self): return self.name @property def all_tags(self): return self.element_type.tags.all() | self.tags.all() tagging_register(Element) class MapElement(Element): @property def style(self): map_theme = self.design.map_theme return self.element_type.styles.filter(map_theme=map_theme).first() @property def json_style(self): style = self.style if style is None: return {} return style.to_json()