Example #1
0
 def test_with_simple_space_delimited_tags(self):
     """ Test with simple space-delimited tags. """
     
     self.assertEquals(parse_tag_input('one'), [u'one'])
     self.assertEquals(parse_tag_input('one two'), [u'one', u'two'])
     self.assertEquals(parse_tag_input('one two three'), [u'one', u'three', u'two'])
     self.assertEquals(parse_tag_input('one one two two'), [u'one', u'two'])
Example #2
0
    def add_search_results(self, request, queryset, search_results):
        for item in queryset:
            meta_content = parse_tag_input(item.tags)
            meta_content += parse_tag_input(item.alias)
            meta_content += [item.term, item.short_definition]
            meta_content = " ".join(meta_content)
            #print "meta: %r" % meta_content

            search_results.add(
                model_instance=item,

                # displayed short_definition of the result hit
                headline="%s: %s" % (item.term, item.short_definition),

                # displayed in the result list
                language=item.language,

                # Link to the hit
                url=item.get_absolute_url(),

                # the main content -> result lines would be cut out from hits in this content
                content=item.get_search_content(request),

                # hits in meta content has a higher score, but the content would not displayed 
                meta_content=meta_content,
            )
 def testDoubleQuotedMultipleWords(self):
     """A completed quote will trigger this. Unclosed quotes are ignored."""
     self.assertEqual([u'one'], parse_tag_input('"one'))
     self.assertEqual([u'one', u'two'], parse_tag_input('"one two'))
     self.assertEqual([u'one', u'three', u'two'], parse_tag_input('"one two three'))
     self.assertEqual([u'one two'], parse_tag_input('"one two"'))
     self.assertEqual([u'a-one', u'a-two and a-three'], parse_tag_input('a-one "a-two and a-three"'))
Example #4
0
    def test_with_simple_space_delimited_tags(self):
        """ Test with simple space-delimited tags. """

        self.assertEquals(parse_tag_input("one"), [u"one"])
        self.assertEquals(parse_tag_input("one two"), [u"one", u"two"])
        self.assertEquals(parse_tag_input("one two three"), [u"one", u"three", u"two"])
        self.assertEquals(parse_tag_input("one one two two"), [u"one", u"two"])
Example #5
0
    def test_with_comma_delimited_multiple_words(self):
        """ Test with comma-delimited multiple words.
            An unquoted comma in the input will trigger this. """

        self.assertEquals(parse_tag_input(",one"), [u"one"])
        self.assertEquals(parse_tag_input(",one two"), [u"one two"])
        self.assertEquals(parse_tag_input(",one two three"), [u"one two three"])
        self.assertEquals(parse_tag_input("a-one, a-two and a-three"), [u"a-one", u"a-two and a-three"])
Example #6
0
    def test_with_double_quoted_multiple_words(self):
        """ Test with double-quoted multiple words.
            A completed quote will trigger this.  Unclosed quotes are ignored. """

        self.assertEquals(parse_tag_input('"one'), [u"one"])
        self.assertEquals(parse_tag_input('"one two'), [u"one", u"two"])
        self.assertEquals(parse_tag_input('"one two three'), [u"one", u"three", u"two"])
        self.assertEquals(parse_tag_input('"one two"'), [u"one two"])
        self.assertEquals(parse_tag_input('a-one "a-two and a-three"'), [u"a-one", u"a-two and a-three"])
Example #7
0
 def test_with_comma_delimited_multiple_words(self):
     """ Test with comma-delimited multiple words.
         An unquoted comma in the input will trigger this. """
         
     self.assertEquals(parse_tag_input(',one'), [u'one'])
     self.assertEquals(parse_tag_input(',one two'), [u'one two'])
     self.assertEquals(parse_tag_input(',one two three'), [u'one two three'])
     self.assertEquals(parse_tag_input('a-one, a-two and a-three'),
         [u'a-one', u'a-two and a-three'])
Example #8
0
    def test_with_comma_delimited_multiple_words(self):
        """ Test with comma-delimited multiple words.
            An unquoted comma in the input will trigger this. """

        self.assertEquals(parse_tag_input(',one'), [u'one'])
        self.assertEquals(parse_tag_input(',one two'), [u'one two'])
        self.assertEquals(parse_tag_input(',one two three'),
                          [u'one two three'])
        self.assertEquals(parse_tag_input('a-one, a-two and a-three'),
                          [u'a-one', u'a-two and a-three'])
Example #9
0
    def test_with_double_quoted_multiple_words(self):
        """ Test with double-quoted multiple words.
            A completed quote will trigger this.  Unclosed quotes are ignored. """

        self.assertEquals(parse_tag_input('"one'), [u'one'])
        self.assertEquals(parse_tag_input('"one two'), [u'one', u'two'])
        self.assertEquals(parse_tag_input('"one two three'),
                          [u'one', u'three', u'two'])
        self.assertEquals(parse_tag_input('"one two"'), [u'one two'])
        self.assertEquals(parse_tag_input('a-one "a-two and a-three"'),
                          [u'a-one', u'a-two and a-three'])
Example #10
0
    def test_with_comma_delimited_multiple_words(self):
        """ Test with comma-delimited multiple words.
            An unquoted comma in the input will trigger this. """

        self.assertEquals(parse_tag_input(",one"), [u"one"])
        self.assertEquals(parse_tag_input(",one two"), [u"one two"])
        self.assertEquals(parse_tag_input(",one two three"), [u"one two three"])
        self.assertEquals(
            parse_tag_input("a-one, a-two and a-three"),
            [u"a-one", u"a-two and a-three"],
        )
    def update_tags(self, obj, tag_names):
        """
        Update tags associated with an object.
        """
        ctypes = ctypes_leading_to(obj)
        current_tags = list(self.filter(items__content_type__pk__in=[ctype.pk for ctype in ctypes],
                                          items__object_id=obj.pk))

        updated_tag_names = parse_tag_input(tag_names)
        if settings.FORCE_LOWERCASE_TAGS:
            updated_tag_names = [t.lower() for t in updated_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__in=[ctype.pk for ctype in ctypes],
                                               object_id=obj.pk,
                                               tag__in=tags_for_removal).delete()
        # Add new tags
        current_tag_names = [tag.name for tag in current_tags]
        for robj in get_all_parents_until_registered(obj):
            for tag_name in updated_tag_names:
                if tag_name not in current_tag_names:
                    tag, created = self.get_or_create(name=tag_name)
                    TaggedItem._default_manager.create(tag=tag, object=robj)
Example #12
0
 def clean(self, value):
     value = super(TagField, self).clean(value)
     if value == u'':
         return value
     for tag_name in parse_tag_input(
             value, default_namespace=self.default_namespace):
         try:
             check_tag_length(get_tag_parts(tag_name))
         except (ValueError, e):
             if len(e.args) < 3:
                 raise
             part, max_len = e.args[1:3]
             if part == 'tag':
                 raise forms.ValidationError(
                     _('Each tag may be no more than %s characters long.') %
                     max_len)
             elif part == 'namespace':
                 raise forms.ValidationError(
                     _('Each tag\'s namespace may be no more than %s characters long.'
                       ) % max_len)
             elif part == 'name':
                 raise forms.ValidationError(
                     _('Each tag\'s name may be no more than %s characters long.'
                       ) % max_len)
             elif part == 'value':
                 raise forms.ValidationError(
                     _('Each tag\'s value may be no more than %s characters long.'
                       ) % max_len)
             else:
                 raise
     return value
Example #13
0
def pre_save_handler(sender, instance, **kwargs):
    """
    Intercept attempts to save and sort the tag field alphabetically, so
    we won't have different permutations in the filter list.
    """
    taglist = parse_tag_input(instance.tags)
    instance.tags = taglist_to_string(taglist)
Example #14
0
    def update_tags(self, obj, tag_names):
        """
        Update tags associated with an object.
        """
        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)
        if settings.FORCE_LOWERCASE_TAGS:
            updated_tag_names = [t.lower() for t in updated_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(name=tag_name)
                try:
                    TaggedItem._default_manager.create(tag=tag, object=obj)
                except IntegrityError:
                    # there is a race condition between querying for current_tags above
                    # and calling create() here. another process / transaction
                    # may have already created this tag. This scenario usually occurs
                    # with two concurrent calls to a django model's save() method
                    # if the model has a TagField that is being changed. should be
                    # harmless to pass here since the TaggedItem already exists
                    pass
Example #15
0
    def update_tags(self, obj, tag_names, default_namespace=None, q=None):
        """
        Update tags associated with an object.

        Accepts a ``default_namespace`` parameter that is assigned to tags
        with no namespace specified.
        """
        ctype = ContentType.objects.get_for_model(obj)
        current_tags = self.filter(items__content_type__pk=ctype.pk,
                                   items__object_id=obj.pk)
        if q is not None:
            current_tags = current_tags.filter(q)
        current_tags = list(current_tags)
        updated_tag_names = parse_tag_input(
            tag_names, default_namespace=default_namespace)
        if conf.FORCE_LOWERCASE_TAGS:
            updated_tag_names = [t.lower() for t in updated_tag_names]

        # Remove tags which no longer apply
        tags_for_removal = [tag for tag in current_tags \
                            if str(tag) 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 = [str(tag) 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(**get_tag_parts(tag_name))
                TaggedItem._default_manager.create(tag=tag, object=obj)
Example #16
0
    def update_tags(self, obj, tag_names, default_namespace=None, q=None):
        """
        Update tags associated with an object.

        Accepts a ``default_namespace`` parameter that is assigned to tags
        with no namespace specified.
        """
        ctype = ContentType.objects.get_for_model(obj)
        current_tags = self.filter(items__content_type__pk=ctype.pk,
            items__object_id=obj.pk)
        if q is not None:
            current_tags = current_tags.filter(q)
        current_tags = list(current_tags)
        updated_tag_names = parse_tag_input(tag_names,
            default_namespace=default_namespace)
        if conf.FORCE_LOWERCASE_TAGS:
            updated_tag_names = [t.lower() for t in updated_tag_names]

        # Remove tags which no longer apply
        tags_for_removal = [tag for tag in current_tags \
                            if unicode(tag) 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 = [unicode(tag) 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(**get_tag_parts(tag_name))
                TaggedItem._default_manager.create(tag=tag, object=obj)
Example #17
0
    def update_tags(self, obj, tag_names):
        """
        Update tags associated with an object.
        """
        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)
        if settings.FORCE_LOWERCASE_TAGS:
            updated_tag_names = [t.lower() for t in updated_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(name=tag_name)
                try:
                    TaggedItem._default_manager.create(tag=tag, object=obj)
                except:
                    pass
Example #18
0
    def add_tag(self, obj, tag_name):
        """
        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]
        if settings.FORCE_LOWERCASE_TAGS:
            tag_name = tag_name.lower()
        ctype = ContentType.objects.get_for_model(obj)

        ###ADDED BY RHIZOME TO DISTINGUISH TYPE 
        post_content_type, artwork_content_type, member_exhibition_content_type = get_content_types()
                        
        if ctype == post_content_type:        
            tag, created = self.get_or_create(slug=tag_name, type="editorial")
        if ctype == artwork_content_type:        
            tag, created = self.get_or_create(slug=tag_name, type="artbase")
        if ctype == member_exhibition_content_type:
            tag, created = self.get_or_create(slug=tag_name, type="member_exhibition")

        TaggedItem._default_manager.get_or_create(
            tag=tag, content_type=ctype, object_id=obj.pk)
Example #19
0
    def update_tags(self, obj, tag_names, user=None):
        """
        Update tags associated with an object.
        user - the user adding the new tags
        """

        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)
        if settings.FORCE_LOWERCASE_TAGS:
            updated_tag_names = [t.lower() for t in updated_tag_names]

        updated_tag_name_slugs = [slugify(t) for t in updated_tag_names]
        update_tag_name_dict = dict(zip(updated_tag_name_slugs, updated_tag_names))

        # Remove tags which no longer apply
        tags_for_removal = [tag for tag in current_tags \
                            if tag.slug not in updated_tag_name_slugs]
        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]
        current_tag_name_slugs = [tag.slug for tag in current_tags]
        for tag_slug in updated_tag_name_slugs:
            if tag_slug not in current_tag_name_slugs:
                tag_name = update_tag_name_dict[tag_slug]
                tag, created = self.get_or_create(slug=tag_slug, defaults=dict(name=tag_name))
                TaggedItem._default_manager.create(tag=tag, object=obj, user=user)
Example #20
0
def pre_save_handler(sender, instance, **kwargs):
    """
    Intercept attempts to save and sort the tag field alphabetically, so
    we won't have different permutations in the filter list.
    """
    taglist = parse_tag_input(instance.tags)
    instance.tags = taglist_to_string(taglist)
Example #21
0
    def update_tags(self, obj, tag_names, labels=None):
        """
        Update tags associated with an object.
        """
        ctype = ContentType.objects.get_for_model(obj)

        ##TODO: This fails silently in non-rel when it should not
        #current_tags = list(self.filter(items__content_type__pk=ctype.pk,
        #                                items__object_id=obj.pk))
        ##This works, divided into two queries
        items = TaggedItem.objects.filter(content_type__pk=ctype.pk, object_id=obj.pk)
        current_tags = self.filter(pk__in=[item.tag_id for item in items])

        updated_tag_names = parse_tag_input(tag_names)
        if settings.FORCE_LOWERCASE_TAGS:
            updated_tag_names = [t.lower() for t in updated_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(name=tag_name)
                TaggedItem._default_manager.create(tag=tag, object=obj)
Example #22
0
 def add_tag(self, obj, tag_name):
     """
     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]
     if settings.FORCE_LOWERCASE_TAGS:
         tag_name = tag_name.lower()
     tag, created = self.get_or_create(slug=slugify(tag_name),
                                       defaults={'name': tag_name})
     if not created:
         # check if there is a preferred synonym for this tag
         try:
             related_tag = RelatedTag.objects.get(tag=tag, relation_type='=>')
         except RelatedTag.DoesNotExist:
             pass
         else:
             # there is a preferred synonym; use it instead of the original
             tag = related_tag.related_tag
     ctype = ContentType.objects.get_for_model(obj)
     TaggedItem._default_manager.get_or_create(
         tag=tag, content_type=ctype, object_id=obj.pk)
Example #23
0
 def save(self):
     self.rendered = markdown(self.description,
                              ['video', 'codehilite', 'urlize'])
     self.tags = ','.join([slugify(x) for x in parse_tag_input(self.tags)])
     self.slug = '%s-%s' % (slugify(self.title[:30])
                            or 'sin-titulo', self.pk)
     super(Leak, self).save()
Example #24
0
    def update_tags(self, obj, tag_names):
        """
        Update tags associated with an object.
        """
        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)
        if settings.FORCE_LOWERCASE_TAGS:
            updated_tag_names = [t.lower() for t in updated_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(name=tag_name)
                TaggedItem._default_manager.create(tag=tag, object=obj)
 def testBadUsersNaughtyUsers(self):
     self.assertEqual([], parse_tag_input(None))
     self.assertEqual([], parse_tag_input(''))
     self.assertEqual([], parse_tag_input('"'))
     self.assertEqual([], parse_tag_input('""'))
     self.assertEqual([], parse_tag_input('"' * 7))
     self.assertEqual([], parse_tag_input(',,,,,,'))
     self.assertEqual([u','], parse_tag_input('",",",",",",","'))
     self.assertEqual([u'a-one', u'a-three', u'a-two', u'and'], parse_tag_input('a-one "a-two" and "a-three'))
Example #26
0
def is_tag_list(value):
    """
	Validates that ``value`` is a valid list of tags.
	"""
    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
Example #27
0
 def render(self, name, value, attrs=None):
     output = ['<div class="tagbox" id="id_%s">' % (name)]
     if value:
         tags = parse_tag_input(value)
         for tag in tags:
             output.append(tag + ",")
     output.append("</div>")
     return mark_safe(u"\n".join(output))
Example #28
0
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)
Example #29
0
def parse_tag_input_local(input, max_count = 5):
    """
    Given a list of comma separated tags, return the parsed tags as a list.  Maximum
    max_count tags returned.
    """
    words = parse_tag_input(input)
    words = [word.replace(' ', '-') for word in words][0:max_count]
    return words
Example #30
0
 def append_user_tags(self, tags):
     user_tags = parse_tag_input(self.user.tags)
     print(user_tags)
     print(tags)
     merged = list(set(tags + user_tags))
     print(merged)
     self.user.tags = ','.join(merged)
     self.user.save()
Example #31
0
 def clean(self, value):
     value = super(TagField, self).clean(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
Example #32
0
 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]) > settings.MAX_TAG_LENGTH:
         raise forms.ValidationError(_("A tag may be no more than %s characters long.") % settings.MAX_TAG_LENGTH)
     return value
Example #33
0
 def save(self, *args, **kwargs):
     self.rendered = markdown(
         self.description, 
         ['ltmo.mdx_urlize', 'ltmo.mdx_video', 'codehilite']
     )
     self.tags = ','.join([slugify(x) for x in parse_tag_input(self.tags)])
     self.slug = '%s-%s' %(slugify(self.title[:30]) or 'sin-titulo', self.pk)
     super(Leak, self).save(*args, **kwargs)
Example #34
0
 def clean(self, value):
     value = super(TagField, self).clean(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
Example #35
0
 def testBadUsersNaughtyUsers(self):
     self.assertEqual([], parse_tag_input(None))
     self.assertEqual([], parse_tag_input(''))
     self.assertEqual([], parse_tag_input('"'))
     self.assertEqual([], parse_tag_input('""'))
     self.assertEqual([], parse_tag_input('"' * 7))
     self.assertEqual([], parse_tag_input(',,,,,,'))
     self.assertEqual([u','], parse_tag_input('",",",",",",","'))
     self.assertEqual([u'a-one', u'a-three', u'a-two', u'and'],
                      parse_tag_input('a-one "a-two" and "a-three'))
Example #36
0
 def render(self, context):
     tags = parse_tag_input(self.tags_string.resolve(context))
     tags = ['<a href="%s" rel="tag">%s</a>' % (url_reverse(self.urlname, kwargs={'tag':t}), t) for t in tags]
     if len(tags) > 2:
         first_part = self.junctor.join(tags[:-1])
         return first_part + self.last_junctor + tags[-1]
     if len(tags) == 2:
         return self.last_junctor.join(tags)
     return self.junctor.join(tags)
Example #37
0
    def clean_tags(self):
        tag_list = parse_tag_input(self.cleaned_data['tags'])
        tags = ''
        for tag in tag_list:
            tag = tag.replace(' ', '-')
            if tag not in tags:
                tags += tag + ","

        return tags
Example #38
0
 def test_with_naughty_input(self):
     """ Test with naughty input. """
     # Bad users! Naughty users!
     self.assertEqual(parse_tag_input(None), [])
     self.assertEqual(parse_tag_input(""), [])
     self.assertEqual(parse_tag_input('"'), [])
     self.assertEqual(parse_tag_input('""'), [])
     self.assertEqual(parse_tag_input('"' * 7), [])
     self.assertEqual(parse_tag_input(",,,,,,"), [])
     self.assertEqual(parse_tag_input('",",",",",",","'), [","])
     self.assertEqual(parse_tag_input('a-one "a-two" and "a-three'), ["a-one", "a-three", "a-two", "and"])
Example #39
0
    def __init__(self, *args, **kwargs):
        super(UserAddForm, self).__init__(*args, **kwargs)

        tag_string = self.instance.profile.tag_list
        self.initial['tag_list'] = parse_tag_input(tag_string)

        self.fields['tag_list'].choices = Tag.objects.all().values_list('name', 'name')
        self.fields['organisation'].initial = self.instance.profile.organisation
        self.fields['trust_level'].initial = self.instance.profile.trust_level
        self.fields['trust_level'].label = 'Trusted user'
Example #40
0
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)
Example #41
0
 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]) > settings.MAX_TAG_LENGTH:
         raise forms.ValidationError(
             _('A tag may be no more than %s characters long.') %
                 settings.MAX_TAG_LENGTH)
     return value
Example #42
0
 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]) > getattr(settings, 'MAX_TAG_LENGTH', MAX_TAG_LENGTH):
         raise forms.ValidationError(
             _('A tag may be no more than %s characters long.') %
                 getattr(settings, 'MAX_TAG_LENGTH', MAX_TAG_LENGTH))
     return value
Example #43
0
def is_tag_list(value):
    """
    Validates that ``value`` is a valid list of tags.
    """
    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
Example #44
0
    def _pre_save(self, **kwargs):  #signal, sender, instance):
        """
        Save tags back to the database
        """
        tags = self._get_instance_tag_cache(kwargs['instance'])
        tags = parse_tag_input(tags)

        #print 'Tags before: %s' % tags
        instance = kwargs['instance']
        self._set_instance_tag_cache(instance, edit_string_for_tags(tags))
Example #45
0
 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) > getattr(settings, 'MAX_TAG_LENGTH', MAX_TAG_LENGTH):
             raise forms.ValidationError(
                 _('Each tag may be no more than %s characters long.') %
                     getattr(settings, 'MAX_TAG_LENGTH', MAX_TAG_LENGTH))
     return value
Example #46
0
def update_actionbar_tags(request, *objects):

    # split tags on commas unless there is a quote in the input
    nt = request.POST.get('new_tags')
    if '"' in nt:
        new_tags = parse_tag_input(nt)
    else:
        new_tags = filter(None, map(lambda s: s.strip(), nt.split(',')))
    all_tags = parse_tag_input(request.POST.get('all_tags'))
    try:
        update_tags = dict(
            (base64.b32decode(k[11:].replace('_', '=')), v)
            for k, v in request.POST.iteritems()
            if k.startswith('update_tag_')
        )
    except TypeError:
        # Could not decode base32 encoded tag names
        update_tags = ()

    remove_tags = [
        tag_name
        for tag_name in all_tags
        if tag_name not in update_tags.keys() and tag_name not in new_tags
    ]

    for obj in objects:
        wrapper = OwnedWrapper.objects.get_for_object(
            user=request.user, object=obj)
        for tag_name, action in update_tags.iteritems():
            if action == 'mixed':
                # Don't need to change anything
                continue
            elif action == 'true':
                # Add tag to all selected presentations
                Tag.objects.add_tag(wrapper, '"%s"' % tag_name)
        for tag_name in new_tags:
            Tag.objects.add_tag(wrapper, '"%s"' % tag_name)
        for tag_name in remove_tags:
            keep_tags = Tag.objects.get_for_object(
                wrapper).exclude(name=tag_name).values_list('name')
            Tag.objects.update_tags(
                wrapper, ' '.join(map(lambda s: '"%s"' % s, keep_tags)))
Example #47
0
    def test_with_naughty_input(self):
        """ Test with naughty input. """

        # Bad users! Naughty users!
        self.assertEquals(parse_tag_input(None), [])
        self.assertEquals(parse_tag_input(''), [])
        self.assertEquals(parse_tag_input('"'), [])
        self.assertEquals(parse_tag_input('""'), [])
        self.assertEquals(parse_tag_input('"' * 7), [])
        self.assertEquals(parse_tag_input(',,,,,,'), [])
        self.assertEquals(parse_tag_input('",",",",",",","'), [u','])
        self.assertEquals(parse_tag_input('a-one "a-two" and "a-three'),
                          [u'a-one', u'a-three', u'a-two', u'and'])
Example #48
0
 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) > getattr(settings, 'MAX_TAG_LENGTH',
                                    MAX_TAG_LENGTH):
             raise forms.ValidationError(
                 _('Each tag may be no more than %s characters long.') %
                 getattr(settings, 'MAX_TAG_LENGTH', MAX_TAG_LENGTH))
     return value
Example #49
0
    def get_skip_tags(self):
        global SKIP_TAGS_CACHE
        if SKIP_TAGS_CACHE is None:
            #            print "*** Fill skip tags cache"
            self.get_preferences()
            skip_tag_string = self.data.get("skip_tags", DEFAULT_SKIP_TAGS)
            SKIP_TAGS_CACHE = parse_tag_input(skip_tag_string)

#        print "*** skip tags: %r" % SKIP_TAGS_CACHE

        return SKIP_TAGS_CACHE
Example #50
0
def is_tag(value):
    """
    Validates that ``value`` is a valid tag.
    """
    tag_names = parse_tag_input(value)
    if len(tag_names) > 1:
        raise ValidationError(_('Multiple tags were given.'))
    elif len(tag_names[0]) > settings.MAX_TAG_LENGTH:
        raise forms.ValidationError(
            _('A tag may be no more than %s characters long.') %
            settings.MAX_TAG_LENGTH)
    return value
Example #51
0
    def test_with_naughty_input(self):
        """ Test with naughty input. """

        # Bad users! Naughty users!
        self.assertEquals(parse_tag_input(None), [])
        self.assertEquals(parse_tag_input(""), [])
        self.assertEquals(parse_tag_input('"'), [])
        self.assertEquals(parse_tag_input('""'), [])
        self.assertEquals(parse_tag_input('"' * 7), [])
        self.assertEquals(parse_tag_input(",,,,,,"), [])
        self.assertEquals(parse_tag_input('",",",",",",","'), [u","])
Example #52
0
def add_tags(request, type, id):
    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])
    tags = request.POST.get('tags')
    if '"' in tags:
        new_tags = parse_tag_input(tags)
    else:
        new_tags = filter(None, map(lambda s: s.strip(), tags.split(',')))
    ownedwrapper = OwnedWrapper.objects.get_for_object(
        user=request.user, type=type, object_id=id)
    for tag in new_tags:
        Tag.objects.add_tag(ownedwrapper, '"%s"' % tag)
    return HttpResponseRedirect(request.GET.get('next') or '/')
Example #53
0
    def default(self, obj):
        if isinstance(obj, Comment) :
            comment = obj
            #replies = list(comment.comment_set.order_by('created'))
            text=comment.text_version.text
            replies = get_viewable_comments(self.request, comment.comment_set.all(), text)
            
            # can_view == true because of get_viewable_comments filter
            can_moderate = has_perm(self.request, 'can_edit_comment', text)   
            can_edit = has_perm(self.request, 'can_edit_comment', text) or has_own_perm(self.request, 'can_edit_comment_own', text, comment)  
            can_delete = has_perm(self.request, 'can_delete_comment', text) or has_own_perm(self.request, 'can_delete_comment_own', text, comment)
            
            return {'id' : comment.id, 
                    'key' : comment.key,
                    'id_key' : comment.id_key,
                   'created_user_str' : datetime_to_user_str(request_tz_convert(comment.created, self.request)),
                   'modified_user_str' : datetime_to_user_str(request_tz_convert(comment.modified, self.request)),
#                   'created_str' : datetime_to_str(comment.created), # TODO change to a simple number as modified if possible
                   'created' : datetime_to_epoch(comment.created), # TODO change to a simple number as modified if possible
                   'modified' : datetime_to_epoch(comment.modified),  
#                   'modified' : time.mktime(comment.modified.timetuple()),  
#                   'created' : datetime_to_js_date_str(comment.created),
                   'reply_to_id' : comment.reply_to_id,
                   'replies' : replies,
                   'name' : comment.get_name(), 
                   'email' : comment.get_email(), 
                   'logged_author' : (comment.user != None), 
                   'title':comment.title,
                   'content':comment.content, 
                   'content_html':comment.content_html, 
                   'tags': ', '.join(parse_tag_input(comment.tags)), 
                   'category': comment.category,
                   'format': comment.format, 
                   'start_wrapper' : comment.start_wrapper, 
                   'end_wrapper' : comment.end_wrapper,
                   'start_offset' : comment.start_offset, 
                   'end_offset' : comment.end_offset,
                   'state' : comment.state,
                   'permalink' : reverse('text-view-show-comment', args=[text.key, comment.id_key]),
                   # permission
                   'can_edit' : can_edit,
                   'can_delete' : can_delete,
                   'can_moderate' : can_moderate,
                   }
        if isinstance(obj, Tag) :
            tag = obj
            # RBE each time issuing a db request to find comments related to this tag !!! TODO  
            return { 'ids' : [t.id for t in tag.items.all()], 'name' : tag.name, 'font_size' : tag.font_size}            

        return simplejson.JSONEncoder.default(self, obj)
Example #54
0
 def get_context_data(self, **kwargs):
     context = super(SubmitVideoView, self).get_context_data(**kwargs)
     # Provided for backwards-compatibility.
     context['data'] = {
         'link': self.object.website_url,
         'publish_date': self.object.when_published,
         'tags': parse_tag_input(context['form'].initial.get('tags', '')),
         'title': self.object.name,
         'description': self.object.description,
         'thumbnail_url': self.object.thumbnail_url,
         'user': self.object.video_service_user,
         'user_url': self.object.video_service_url,
     }
     return context
Example #55
0
    def clean_tags(self):
        tag_list = parse_tag_input(self.cleaned_data['tags'])
        tags = ''
        for tag in tag_list:
            tag = tag.lower().replace(' ', '-')
            if tag not in tags:
                tags += tag + ","

        # Project name must always be a tag
        group_tag = slugify(self.cleaned_data['name'])
        if group_tag not in tag_list:
            tags = group_tag + ',' + tags

        return tags
Example #56
0
def add_tags(request, type, id):
    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])
    tags = request.POST.get('tags')
    if '"' in tags:
        new_tags = parse_tag_input(tags)
    else:
        new_tags = [_f for _f in [s.strip() for s in tags.split(',')] if _f]
    ownedwrapper = OwnedWrapper.objects.get_for_object(user=request.user,
                                                       type=type,
                                                       object_id=id)
    for tag in new_tags:
        Tag.objects.add_tag(ownedwrapper, '"%s"' % tag)
    return HttpResponseRedirect(
        validate_next_link(request.GET.get('next'), '/'))