def filter(self, qs, value): if not value: return qs if isinstance(value, basestring): value = parse_tag_input(value) elif not isinstance(value, list) and not isinstance(value, tuple): value = [value] return qs.filter(**{"%s__tag__pk__in"%self.name: value}).distinct()
def isTagList(field_data, all_data): """ Validates that ``field_data`` is a valid list of tags. """ for tag_name in parse_tag_input(field_data): if len(tag_name) > settings.MAX_TAG_LENGTH: raise ValidationError( _('Each tag may be no more than %s characters long.') % settings.MAX_TAG_LENGTH)
def clean(self, value): value = super(TagField, self).clean(value) if value == u'': return value for tag_name in parse_tag_input(value): if len(tag_name) > settings.MAX_TAG_LENGTH: raise forms.ValidationError( _('Each tag may be no more than %s characters long.') % settings.MAX_TAG_LENGTH) return value
def clean_name(self): value = self.cleaned_data['name'] tag_names = parse_tag_input(value) if len(tag_names) > 1: raise forms.ValidationError(_('Multiple tags were given.')) elif len(tag_names[0]) > MAX_TAG_LENGTH: raise forms.ValidationError( _('A tag may be no more than %s characters long.') % MAX_TAG_LENGTH) return value
def isTag(field_data, all_data): """ Validates that ``field_data`` is a valid tag. """ tag_names = parse_tag_input(field_data) if len(tag_names) > 1: raise ValidationError(_('Multiple tags were given.')) elif len(tag_names[0]) > settings.MAX_TAG_LENGTH: raise ValidationError( _('A tag may be no more than %s characters long.') % settings.MAX_TAG_LENGTH)
def add_tag(self, obj, tag_name): from models import TaggedItem """ Associates the given object with a tag. """ tag_names = parse_tag_input(tag_name) if not len(tag_names): raise AttributeError(_('No tags were given: "%s".') % tag_name) if len(tag_names) > 1: raise AttributeError(_('Multiple tags were given: "%s".') % tag_name) tag_name = tag_names[0] tag, created = self.get_or_create(tag_name) ctype = ContentType.objects.get_for_model(obj) TaggedItem._default_manager.get_or_create( tag=tag, content_type=ctype, object_id=obj.pk)
def update_tags(self, obj, labels): u"""Update tags of the obj by `labels`""" ctype = ContentType.objects.get_for_model(obj) current_tags = list(self.filter(items__content_type=ctype, items__object_id=obj.pk)) updated_tag_labels = parse_tag_input(labels) # Remove all tags not in updated_tag_labels tags_for_removal = [tag for tag in current_tags if tag.label not in updated_tag_labels] if len(tags_for_removal): TaggedItem._default_manager.filter( content_object=obj, tag__in=tags_for_removal).delete() # Append new tags current_tag_labels = [tag.label for tag in current_tags] for tag_label in updated_tag_labels: if not tag_label in current_tag_labels: tag = self.get_or_create(label=tag_label)[0] TaggedItem._default_manager.create(tag=tag, content_object=obj)
def sort_tags(request, *args, **kwargs): form = MultiTagForm(request.POST) if form.is_valid(): instance_list = [] errors = [] obj = get_object_from_ct(form.cleaned_data['content_type'], form.cleaned_data['object_id']) for i, label in enumerate(parse_tag_input(form.cleaned_data['labels'])): tagged_item = Tag.objects.add_tag(obj, label) tagged_item.order = i tagged_item.save() instance_list.append(tagged_item.json()) data = { 'status': 'ok', 'instance_list': instance_list, } return JsonResponse(data) else: errors = [unicode(striptags("%s: %s" % (k, v))) for k, v in form.errors.iteritems()] return JsonResponse({'status': 'faield', 'errors': errors})
def create_tags(request, *args, **kwargs): form = MultiTagForm(request.POST) if form.is_valid(): obj = get_object_from_ct(form.cleaned_data['content_type'], form.cleaned_data['object_id']) instance_list = [] errors = [] for label in parse_tag_input(form.cleaned_data['labels']): try: tagged_item = Tag.objects.add_tag(obj, label, ignore_duplicate=False) instance_list.append(tagged_item.json()) except exceptions.DuplicateError: errors.append(_(u"Tag %(label)s is duplicated.") % {'label': label}) data = { 'status': 'ok', 'instance_list': instance_list, } if len(errors) > 0: data['errors'] = errors return JsonResponse(data) else: errors = [unicode(striptags("%s: %s" % (k, v))) for k, v in form.errors.iteritems()] return JsonResponse({'status': 'failed', 'errors': errors})
def reconstruct(self, obj, labels): """Reconstruct tags for object via label list Args: obj - the target model instance labels - a list of tag label """ ctype = ContentType.objects.get_for_model(obj) current_tags = list(Tag.objects.filter(items__content_type=ctype, items__object_id=obj.pk)) updated_tag_labels = parse_tag_input(labels) # Remove all tags not in updated_tag_labels tags_for_removal = [tag for tag in current_tags if tag.label not in updated_tag_labels] if len(tags_for_removal): self.filter( content_type=ctype, object_id=obj.pk, tag__in=tags_for_removal).delete() # Append new tags current_tag_labels = [tag.label for tag in current_tags] for tag_label in updated_tag_labels: if not tag_label in current_tag_labels: self.add_or_get(obj, tag_label)
def delete_tags(request, *args, **kwargs): form = MultiTagForm(request.POST) if form.is_valid(): instance_list = [] errors = [] obj = get_object_from_ct(form.cleaned_data['content_type'], form.cleaned_data['object_id']) for label in parse_tag_input(form.cleaned_data['labels']): try: tagged_item = Tag.objects.remove_tag(obj, label) instance_list.append(tagged_item.json()) except exceptions.DeletingFrozenTagError: errors.append(_(u"Unable to delete Tag %(label)s while it is frozen.") % {'label': label}) except (Tag.DoesNotExist, TaggedItem.DoesNotExist): errors.append(_(u"Tag %(label)s is not defined.") % {'label': label}) data = { 'status': 'ok', 'instance_list': instance_list, } if len(errors) > 0: data['errors'] = errors return JsonResponse(data) else: errors = [unicode(striptags("%s: %s" % (k, v))) for k, v in form.errors.iteritems()] return JsonResponse({'status': 'faield', 'errors': errors})
def update_tags(self, obj, tag_names): """ Update tags associated with an object. """ from models import TaggedItem ctype = ContentType.objects.get_for_model(obj) current_tags = list(self.filter(items__content_type__pk=ctype.pk, items__object_id=obj.pk)) updated_tag_names = parse_tag_input(tag_names) # Remove tags which no longer apply tags_for_removal = [tag for tag in current_tags \ if tag.name not in updated_tag_names] if len(tags_for_removal): TaggedItem._default_manager.filter(content_type__pk=ctype.pk, object_id=obj.pk, tag__in=tags_for_removal).delete() # Add new tags current_tag_names = [tag.name for tag in current_tags] for tag_name in updated_tag_names: if tag_name not in current_tag_names: tag, created = self.get_or_create(tag_name) TaggedItem._default_manager.create(tag=tag, content_object=obj)
def freeze_tags(request, *args, **kwargs): form = MultiTagForm(request.POST) if form.is_valid(): instance_list = [] errors = [] obj = get_object_from_ct(form.cleaned_data['content_type'], form.cleaned_data['object_id']) # Validation if getattr(obj, 'author', None) != request.user and getattr(obj, 'user', None) != request.user: return JsonResponse({'status': 'failed', 'errors': [_('Permission denied')]}) for label in parse_tag_input(form.cleaned_data['labels']): try: tagged_item = Tag.objects.freeze_tag(obj, label) instance_list.append(tagged_item.json()) except (Tag.DoesNotExist, TaggedItem.DoesNotExist): errors.append(_(u"Tag %(label)s is not defined.") % {'label': label}) data = { 'status': 'ok', 'instance_list': instance_list, } if len(errors) > 0: data['errors'] = errors return JsonResponse(data) else: errors = [unicode(striptags("%s: %s" % (k, v))) for k, v in form.errors.iteritems()] return JsonResponse({'status': 'faield', 'errors': errors})