def test_add_tag(self): # start off in a known, mildly interesting state Tag.objects.update_tags(self.dead_parrot, 'foo bar baz') tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEqual(len(tags), 3) self.assertTrue(get_tag('bar') in tags) self.assertTrue(get_tag('baz') in tags) self.assertTrue(get_tag('foo') in tags) # try to add a tag that already exists Tag.objects.add_tag(self.dead_parrot, 'foo') tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEqual(len(tags), 3) self.assertTrue(get_tag('bar') in tags) self.assertTrue(get_tag('baz') in tags) self.assertTrue(get_tag('foo') in tags) # now add a tag that doesn't already exist Tag.objects.add_tag(self.dead_parrot, 'zip') tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEqual(len(tags), 4) self.assertTrue(get_tag('zip') in tags) self.assertTrue(get_tag('bar') in tags) self.assertTrue(get_tag('baz') in tags) self.assertTrue(get_tag('foo') in tags)
def test_add_tag(self): # start off in a known, mildly interesting state Tag.objects.update_tags(self.dead_parrot, "foo bar baz") tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 3) self.failUnless(get_tag("bar") in tags) self.failUnless(get_tag("baz") in tags) self.failUnless(get_tag("foo") in tags) # try to add a tag that already exists Tag.objects.add_tag(self.dead_parrot, "foo") tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 3) self.failUnless(get_tag("bar") in tags) self.failUnless(get_tag("baz") in tags) self.failUnless(get_tag("foo") in tags) # now add a tag that doesn't already exist Tag.objects.add_tag(self.dead_parrot, "zip") tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 4) self.failUnless(get_tag("zip") in tags) self.failUnless(get_tag("bar") in tags) self.failUnless(get_tag("baz") in tags) self.failUnless(get_tag("foo") in tags)
def test_add_tag(self): # start off in a known, mildly interesting state Tag.objects.update_tags(self.dead_parrot, 'foo bar baz') tags = Tag.objects.get_for_object(self.dead_parrot) ##TODO: for some reason this doesn't work #self.assertEquals(len(tags), 3) ## But this does! self.assertEquals(len(list(tags)), 3) self.failUnless(get_tag('bar') in tags) self.failUnless(get_tag('baz') in tags) self.failUnless(get_tag('foo') in tags) # try to add a tag that already exists Tag.objects.add_tag(self.dead_parrot, 'foo') tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 3) self.failUnless(get_tag('bar') in tags) self.failUnless(get_tag('baz') in tags) self.failUnless(get_tag('foo') in tags) # now add a tag that doesn't already exist Tag.objects.add_tag(self.dead_parrot, 'zip') tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 4) self.failUnless(get_tag('zip') in tags) self.failUnless(get_tag('bar') in tags) self.failUnless(get_tag('baz') in tags) self.failUnless(get_tag('foo') in tags)
def relate(self, tags, relation_type='~', related_tags=[], force_create=False): ''' Relates each tag in a list of tags with each tag in a list of related_tags with the given relation type. Tag lists can be Tag instances or strings. Relations are created symmetrically. If force_create = True, tags are created from string if they do not already exist. If just a list of tags are given, it calls relate_all() to relate them with each other using '~' relation. Updates existing relations if needed. ''' #TODO: WTF tags = get_tag_list(tags) if related_tags == []: self.relate_all(tags) else: related_tags = get_tag_list(related_tags) for tag in tags: tag = get_tag(tag) if tag and tag.is_valid: for related_tag in related_tags: related_tag = get_tag(related_tag) if related_tag and related_tag.is_valid: if tag != related_tag: rel, c = RelatedTag.objects.get_or_create(tag=tag, related_tag=related_tag, defaults={'relation_type': relation_type, 'count': 1}) if not c: rel.count += 1 # check if the existing relation is correct if rel.relation_type != relation_type: rel.relation_type = relation_type rel.save()
def test_update_via_tags_field(self): f1 = FormTest.objects.create(tags=u'test3 test2 test1') tags = Tag.objects.get_for_object(f1) test1_tag = get_tag('test1') test2_tag = get_tag('test2') test3_tag = get_tag('test3') self.failUnless(None not in (test1_tag, test2_tag, test3_tag)) ##TODO: for some reason this doesn't work #self.assertEquals(len(tags), 3) ## But this does! self.assertEquals(len(list(tags)), 3) self.failUnless(test1_tag in tags) self.failUnless(test2_tag in tags) self.failUnless(test3_tag in tags) f1.tags = u'test4' f1.save() tags = Tag.objects.get_for_object(f1) test4_tag = get_tag('test4') self.assertEquals(len(tags), 1) self.assertEquals(tags[0], test4_tag) f1.tags = '' f1.save() tags = Tag.objects.get_for_object(f1) self.assertEquals(len(tags), 0)
def test_create_with_tags_specified(self): f1 = FormTest.objects.create(tags=u'test3 test2 test1') tags = Tag.objects.get_for_object(f1) test1_tag = get_tag('test1') test2_tag = get_tag('test2') test3_tag = get_tag('test3') self.failUnless(None not in (test1_tag, test2_tag, test3_tag)) self.assertEquals(len(tags), 3) self.failUnless(test1_tag in tags) self.failUnless(test2_tag in tags) self.failUnless(test3_tag in tags)
def test_create_with_tags_specified(self): f1 = FormTest.objects.create(tags="test3 test2 test1") tags = Tag.objects.get_for_object(f1) test1_tag = get_tag("test1") test2_tag = get_tag("test2") test3_tag = get_tag("test3") self.assertTrue(None not in (test1_tag, test2_tag, test3_tag)) self.assertEqual(len(tags), 3) self.assertTrue(test1_tag in tags) self.assertTrue(test2_tag in tags) self.assertTrue(test3_tag in tags)
def test_update_tags_with_none(self): # start off in a known, mildly interesting state Tag.objects.update_tags(self.dead_parrot, "foo bar baz") tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEqual(len(tags), 3) self.assertTrue(get_tag("bar") in tags) self.assertTrue(get_tag("baz") in tags) self.assertTrue(get_tag("foo") in tags) Tag.objects.update_tags(self.dead_parrot, None) tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEqual(len(tags), 0)
def testMergeTagsCreatesSynonyms(self): first = TestItem(title = 'first', tags = 'one, two') first.save() second = TestItem(title = 'second', tags = 'second') second.save() self.assertEqual([], [s.name for s in get_tag('two').synonyms.all()]) ctype = model_to_ctype(TestItem) merge('two', 'second', ctype) self.assertEqual(['second'], [s.name for s in get_tag('two').synonyms.all()])
def test_update_tags_with_none(self): # start off in a known, mildly interesting state Tag.objects.update_tags(self.dead_parrot, 'foo bar baz') tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 3) self.failUnless(get_tag('bar') in tags) self.failUnless(get_tag('baz') in tags) self.failUnless(get_tag('foo') in tags) Tag.objects.update_tags(self.dead_parrot, None) tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 0)
def test_add_tag_invalid_input_no_tags_specified(self): # start off in a known, mildly interesting state Tag.objects.update_tags(self.dead_parrot, "foo bar baz") tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 3) self.failUnless(get_tag("bar") in tags) self.failUnless(get_tag("baz") in tags) self.failUnless(get_tag("foo") in tags) try: Tag.objects.add_tag(self.dead_parrot, " ") except AttributeError, ae: self.assertEquals(str(ae), 'No tags were given: " ".')
def test_add_tag_invalid_input_multiple_tags_specified(self): # start off in a known, mildly interesting state Tag.objects.update_tags(self.dead_parrot, 'foo bar baz') tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 3) self.failUnless(get_tag('bar') in tags) self.failUnless(get_tag('baz') in tags) self.failUnless(get_tag('foo') in tags) try: Tag.objects.add_tag(self.dead_parrot, 'one two') except AttributeError, ae: self.assertEquals(str(ae), 'Multiple tags were given: "one two".')
def test_create_with_tags_specified(self): f1 = FormTest.objects.create(tags=u'test3 test2 test1') tags = Tag.objects.get_for_object(f1) test1_tag = get_tag('test1') test2_tag = get_tag('test2') test3_tag = get_tag('test3') self.failUnless(None not in (test1_tag, test2_tag, test3_tag)) ##TODO: for some reason this doesn't work #self.assertEquals(len(tags), 3) ## But this does! self.assertEquals(len(list(tags)), 3) self.failUnless(test1_tag in tags) self.failUnless(test2_tag in tags) self.failUnless(test3_tag in tags)
def testMergeTagsWhenSynonymAlreadyExists(self): first = TestItem(title = 'first', tags = 'one, two, blah') first.save() second = TestItem(title = 'second', tags = 'second') second.save() blah = get_tag('blah') blah.synonyms.create(name='second') self.assertEqual([], [s.name for s in get_tag('two').synonyms.all()]) ctype = model_to_ctype(TestItem) merge('two', 'second', ctype) self.assertEqual([], [s.name for s in get_tag('two').synonyms.all()]) self.assertEqual(['second'], [s.name for s in get_tag('blah').synonyms.all()])
def test_update_tags_with_none(self): # start off in a known, mildly interesting state Tag.objects.update_tags(self.dead_parrot, 'foo bar baz') tags = Tag.objects.get_for_object(self.dead_parrot) ##TODO: for some reason this doesn't work #self.assertEquals(len(tags), 3) ## But this does! self.assertEquals(len(list(tags)), 3) self.failUnless(get_tag('bar') in tags) self.failUnless(get_tag('baz') in tags) self.failUnless(get_tag('foo') in tags) Tag.objects.update_tags(self.dead_parrot, None) tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 0)
def get_object(self, bits): # In case of "/rss/beats/0613/foo/bar/baz/", or other such clutter, # check that bits has only one member. if len(bits) != 1: raise ObjectDoesNotExist tag = get_tag(bits[0]) return tag
def by_tag(request, tag, qtype=None): tag_instance = get_tag(tag) if tag_instance is None: raise Http404() queryset = Book.objects.all() queryset = TaggedItem.objects.get_by_model(queryset, tag_instance) return _book_list(request, queryset, qtype, list_by="by-tag", tag=tag_instance)
def vote_tag(request, tag): tag_instance = get_tag(tag) if tag_instance is None: raise Http404(_('No Tag found matching "%s".') % tag) extra_context = {'tag':tag_instance} extra_context['tag_url'] = reverse('vote-tag',args=[tag_instance]) if 'member' in request.GET: extra_context['member'] = get_object_or_404(Member, pk=request.GET['member']) extra_context['member_url'] = reverse('member-detail',args=[extra_context['member'].id]) extra_context['title'] = ugettext_lazy('Votes tagged %(tag)s by %(member)s') % {'tag': tag, 'member':extra_context['member'].name} qs = extra_context['member'].votes.all() else: # only tag is given extra_context['title'] = ugettext_lazy('Votes tagged %(tag)s') % {'tag': tag} qs = Vote queryset = TaggedItem.objects.get_by_model(qs, tag_instance) vote_attendence = [v.votes.all() for v in TaggedItem.objects.get_by_model(Vote, tag_instance)] d = {} for vote in vote_attendence: for v in vote: d[v] = d.get(v,0)+1 # now d is a dict: MK -> number of votes in this tag mks = d.keys() for mk in mks: mk.count = d[mk] average = float(sum([mk.count for mk in mks]))/len(mks) mks = [mk for mk in mks if mk.count>=average] mks = tagging.utils.calculate_cloud(mks) extra_context['members'] = mks return object_list(request, queryset, #return tagged_object_list(request, queryset_or_model=qs, tag=tag, template_name='laws/vote_list_by_tag.html', extra_context=extra_context)
def lfc_tagged_object_list(request, slug, tag, language=None, template_name="lfc_blog/tag.html"): """Displays blog entries for the given tag. """ if tag is None: raise AttributeError(_('tagged_object_list must be called with a tag.')) tag_instance = get_tag(tag) if tag_instance is None: raise Http404(_('No Tag found matching "%s".') % tag) blog = traverse_object(request, slug) queryset = BlogEntry.objects.filter(parent=blog) entries = [] for entry in TaggedItem.objects.get_by_model(queryset, tag_instance): if entry.has_permission(request.user, "view"): entries.append(entry) return render_to_response(template_name, RequestContext(request, { "slug" : slug, "blog" : blog, "entries" : entries, "tag" : tag, "lfc_context" : blog, }));
def tagged_objects(content_type = None, tag = None, related_tags = False, related_tag_counts = True, **kwargs): """ Returns a queryset of objects of a target content type with the given tag and a list of related tags if related_tags = True. """ if content_type is None: raise AttributeError(_('tagged_objects must be called with a content type')) else: try: model_content_type = ContentType.objects.get(id = int(content_type)) except ObjectDoesNotExist: raise AttributeError(_('tagged_objects must be called with a valid content type')) if tag is None: raise AttributeError(_('tagged_objects must be called with a tag.')) tag_instance = get_tag(tag) if tag_instance is None: raise AttributeError(_('tagged_object must be called with a valid tag')) queryset = TaggedItem.objects.get_by_model(model_content_type.model_class(), tag_instance) if related_tags: related_tags_list = \ Tag.objects.related_for_model(tag_instance, queryset, counts = related_tag_counts) else: related_tags_list = [] return queryset, related_tags_list
def get_queryset(self): try: tag = self.kwargs['tag'] except KeyError: raise AttributeError(_('tagged_object_list must be called with a tag.')) tag_instance = get_tag(tag) return TaggedItem.objects.get_by_model(Entry, tag_instance)
def get_queryset(self): """Return a queryset of entries published belonging to the current tag""" self.tag = get_tag(self.kwargs["tag"]) if self.tag is None: raise Http404(_('No Tag found matching "%s".') % self.tag) return TaggedItem.objects.get_by_model(Entry.published.all(), self.tag)
def get_queryset(self, *args, **kwargs): images = Image.objects.all() tag_instance = get_tag('featured') if tag_instance is None: raise Http404(_('No Tag found matching "featured"')) images = TaggedItem.objects.get_by_model(images, tag_instance) return images
def bill_tag(request, tag): tag_instance = get_tag(tag) if tag_instance is None: raise Http404(_('No Tag found matching "%s".') % tag) extra_context = {'tag':tag_instance} extra_context['tag_url'] = reverse('bill-tag',args=[tag_instance]) if 'member' in request.GET: try: member_id = int(request.GET['member']) except ValueError: raise Http404(_('No Member found matching "%s".') % request.GET['member']) extra_context['member'] = get_object_or_404(Member, pk=request.GET['member']) extra_context['member_url'] = reverse('member-detail',args=[extra_context['member'].id]) extra_context['title'] = _('Bills tagged %(tag)s by %(member)s') % {'tag': tag, 'member':extra_context['member'].name} qs = extra_context['member'].bills.all() else: # only tag is given extra_context['title'] = _('Bills tagged %(tag)s') % {'tag': tag} qs = Bill queryset = TaggedItem.objects.get_by_model(qs, tag_instance) bill_proposers = [b.proposers.all() for b in TaggedItem.objects.get_by_model(Bill, tag_instance)] d = {} for bill in bill_proposers: for p in bill: d[p] = d.get(p,0)+1 # now d is a dict: MK -> number of proposals in this tag mks = d.keys() for mk in mks: mk.count = d[mk] mks = tagging.utils.calculate_cloud(mks) extra_context['members'] = mks return object_list(request, queryset, #return tagged_object_list(request, queryset_or_model=qs, tag=tag, template_name='laws/bill_list_by_tag.html', extra_context=extra_context)
def filter_and_order(self, *args, **kwargs): stage = kwargs.get('stage', None) member = kwargs.get('member', None) booklet = kwargs.get('booklet', None) filter_kwargs = {} if stage and stage != 'all': if stage in BILL_AGRR_STAGES: qs = self.filter(BILL_AGRR_STAGES[stage]) else: filter_kwargs['stage__startswith'] = stage qs = self.filter(**filter_kwargs) else: qs = self.all() if kwargs.get('tagged', None): if kwargs['tagged'] == 'false': ct = ContentType.objects.get_for_model(Bill) filter_tagged = TaggedItem.objects.filter(content_type=ct).distinct().values_list('object_id', flat=True) qs = qs.exclude(id__in=filter_tagged) elif kwargs['tagged'] != 'all': qs = TaggedItem.objects.get_by_model(qs,get_tag(kwargs['tagged'])) if booklet: kps = KnessetProposal.objects.filter(booklet_number=booklet).values_list('id',flat=True) if kps: qs = qs.filter(knesset_proposal__in=kps) return qs
def test_add_tag_invalid_input_no_tags_specified(self): # start off in a known, mildly interesting state Tag.objects.update_tags(self.dead_parrot, 'foo bar baz') tags = Tag.objects.get_for_object(self.dead_parrot) ##TODO: for some reason this doesn't work #self.assertEquals(len(tags), 3) ## But this does! self.assertEquals(len(list(tags)), 3) self.failUnless(get_tag('bar') in tags) self.failUnless(get_tag('baz') in tags) self.failUnless(get_tag('foo') in tags) try: Tag.objects.add_tag(self.dead_parrot, ' ') except AttributeError, ae: self.assertEquals(str(ae), 'No tags were given: " ".')
def filter_and_order(self, *args, **kwargs): stage = kwargs.get('stage', None) member = kwargs.get('member', None) pp_id = kwargs.get('pp_id', None) knesset_booklet = kwargs.get('knesset_booklet', None) gov_booklet = kwargs.get('gov_booklet', None) changed_after = kwargs.get('changed_after', None) changed_before = kwargs.get('changed_before', None) filter_kwargs = {} if stage and stage != 'all': if stage in BILL_AGRR_STAGES: qs = self.filter(BILL_AGRR_STAGES[stage]) else: filter_kwargs['stage__startswith'] = stage qs = self.filter(**filter_kwargs) else: qs = self.all() if kwargs.get('tagged', None): if kwargs['tagged'] == 'false': ct = ContentType.objects.get_for_model(Bill) filter_tagged = TaggedItem.objects.filter(content_type=ct).distinct().values_list('object_id', flat=True) qs = qs.exclude(id__in=filter_tagged) elif kwargs['tagged'] != 'all': qs = TaggedItem.objects.get_by_model(qs,get_tag(kwargs['tagged'])) if pp_id: pps = PrivateProposal.objects.filter( proposal_id=pp_id).values_list( 'id', flat=True) if pps: qs = qs.filter(proposals__in=pps) else: qs = qs.none() if knesset_booklet: kps = KnessetProposal.objects.filter( booklet_number=knesset_booklet).values_list( 'id', flat=True) if kps: qs = qs.filter(knesset_proposal__in=kps) else: qs = qs.none() if gov_booklet: gps = GovProposal.objects.filter( booklet_number=gov_booklet).values_list('id', flat=True) if gps: qs = qs.filter(gov_proposal__in=gps) else: qs = qs.none() if changed_after: qs = qs.filter(stage_date__gte=changed_after) if changed_before: qs = qs.filter(stage_date__lte=changed_before) return qs
def get_queryset(self): tag = self.kwargs['tag'] self.tag_instance = get_tag(tag) if self.tag_instance is None: raise Http404(_('No Tag found matching "%s".') % tag) return TaggedItem.objects.get_by_model( self.queryset_or_model, self.tag_instance )
def render(self, context, instance, placeholder): tag_instance = get_tag(settings.NEWSLETTER_TAG) entry = TaggedItem.objects.get_by_model(Entry, tag_instance).order_by('-pub_date')[0] context.update({ 'entry': entry, 'placeholder': placeholder, }) return context
def get_object(self, bits): if len(bits) != 2: raise ObjectDoesNotExist obj = Tag.objects.get(name__exact=bits[0]) tag_instance = get_tag(obj.name) if tag_instance is None: raise Http404, 'No Tag found matching "%s"' % tag return tag_instance
def test_force_lowercase_tags(self): """ Test forcing tags to lowercase. """ with self.settings(FORCE_LOWERCASE_TAGS=True): Tag.objects.update_tags(self.dead_parrot, 'foO bAr Ter') tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 3) foo_tag = get_tag('foo') bar_tag = get_tag('bar') ter_tag = get_tag('ter') self.failUnless(foo_tag in tags) self.failUnless(bar_tag in tags) self.failUnless(ter_tag in tags) with self.settings(FORCE_LOWERCASE_TAGS=True): Tag.objects.update_tags(self.dead_parrot, 'foO bAr baZ') tags = Tag.objects.get_for_object(self.dead_parrot) baz_tag = get_tag('baz') self.assertEquals(len(tags), 3) self.failUnless(bar_tag in tags) self.failUnless(baz_tag in tags) self.failUnless(foo_tag in tags) with self.settings(FORCE_LOWERCASE_TAGS=True): Tag.objects.add_tag(self.dead_parrot, 'FOO') tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 3) self.failUnless(bar_tag in tags) self.failUnless(baz_tag in tags) self.failUnless(foo_tag in tags) with self.settings(FORCE_LOWERCASE_TAGS=True): Tag.objects.add_tag(self.dead_parrot, 'Zip') tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 4) zip_tag = get_tag('zip') self.failUnless(bar_tag in tags) self.failUnless(baz_tag in tags) self.failUnless(foo_tag in tags) self.failUnless(zip_tag in tags) with self.settings(FORCE_LOWERCASE_TAGS=True): f1 = FormTest.objects.create() f1.tags = u'TEST5' f1.save() tags = Tag.objects.get_for_object(f1) test5_tag = get_tag('test5') self.assertEquals(len(tags), 1) self.failUnless(test5_tag in tags) self.assertEquals(f1.tags, u'test5')
def test_update_tags(self): Tag.objects.update_tags(self.dead_parrot, 'foo,bar,"ter"') tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEqual(len(tags), 3) self.assertTrue(get_tag('foo') in tags) self.assertTrue(get_tag('bar') in tags) self.assertTrue(get_tag('ter') in tags) Tag.objects.update_tags(self.dead_parrot, '"foo" bar "baz"') tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEqual(len(tags), 3) self.assertTrue(get_tag('bar') in tags) self.assertTrue(get_tag('baz') in tags) self.assertTrue(get_tag('foo') in tags)
def test_update_tags(self): Tag.objects.update_tags(self.dead_parrot, 'foo,bar,"ter"') tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 3) self.failUnless(get_tag("foo") in tags) self.failUnless(get_tag("bar") in tags) self.failUnless(get_tag("ter") in tags) Tag.objects.update_tags(self.dead_parrot, '"foo" bar "baz"') tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 3) self.failUnless(get_tag("bar") in tags) self.failUnless(get_tag("baz") in tags) self.failUnless(get_tag("foo") in tags)
def tagged_object_list(request, queryset_or_model=None, tag=None, related_tags=False, related_tag_counts=True, **kwargs): """ A thin wrapper around ``django.views.generic.list_detail.object_list`` which creates a ``QuerySet`` containing instances of the given queryset or model tagged with the given tag. In addition to the context variables set up by ``object_list``, a ``tag`` context variable will contain the ``Tag`` instance for the tag. If ``related_tags`` is ``True``, a ``related_tags`` context variable will contain tags related to the given tag for the given model. Additionally, if ``related_tag_counts`` is ``True``, each related tag will have a ``count`` attribute indicating the number of items which have it in addition to the given tag. """ if queryset_or_model is None: try: queryset_or_model = kwargs.pop('queryset_or_model') except KeyError: raise AttributeError(_('tagged_object_list must be called with a queryset or a model.')) if tag is None: try: tag = kwargs.pop('tag') except KeyError: raise AttributeError(_('tagged_object_list must be called with a tag.')) tag_instance = get_tag(tag) if tag_instance is None: raise Http404(_('No Tag found matching "%(tag)s".') % {'tag': tag}) queryset = TaggedItem.objects.get_by_model(queryset_or_model, tag_instance) if not kwargs.has_key('extra_context'): kwargs['extra_context'] = {} kwargs['extra_context']['tag'] = tag_instance if related_tags: kwargs['extra_context']['related_tags'] = \ Tag.objects.related_for_model(tag_instance, queryset_or_model, counts=related_tag_counts) return object_list(request, queryset, **kwargs)
def filter_and_order(self, *args, **kwargs): stage = kwargs.get('stage', None) member = kwargs.get('member', None) booklet = kwargs.get('booklet', None) changed_after = kwargs.get('changed_after', None) changed_before = kwargs.get('changed_before', None) filter_kwargs = {} if stage and stage != 'all': if stage in BILL_AGRR_STAGES: qs = self.filter(BILL_AGRR_STAGES[stage]) else: filter_kwargs['stage__startswith'] = stage qs = self.filter(**filter_kwargs) else: qs = self.all() if kwargs.get('tagged', None): if kwargs['tagged'] == 'false': ct = ContentType.objects.get_for_model(Bill) filter_tagged = TaggedItem.objects.filter( content_type=ct).distinct().values_list('object_id', flat=True) qs = qs.exclude(id__in=filter_tagged) elif kwargs['tagged'] != 'all': qs = TaggedItem.objects.get_by_model(qs, get_tag(kwargs['tagged'])) if booklet: kps = KnessetProposal.objects.filter( booklet_number=booklet).values_list('id', flat=True) if kps: qs = qs.filter(knesset_proposal__in=kps) if changed_after: qs = qs.filter(stage_date__gte=changed_after) if changed_before: qs = qs.filter(stage_date__lte=changed_before) return qs
def vote_tag(request, tag): tag_instance = get_tag(tag) if tag_instance is None: raise Http404(_('No Tag found matching "%s".') % tag) extra_context = {'tag':tag_instance} extra_context['tag_url'] = reverse('vote-tag',args=[tag_instance]) if 'member' in request.GET: extra_context['member'] = get_object_or_404(Member, pk=request.GET['member']) extra_context['member_url'] = reverse('member-detail',args=[extra_context['member'].id]) extra_context['title'] = ugettext_lazy('Votes tagged %(tag)s by %(member)s') % {'tag': tag, 'member':extra_context['member'].name} qs = extra_context['member'].votes.all() else: # only tag is given extra_context['title'] = ugettext_lazy('Votes tagged %(tag)s') % {'tag': tag} qs = Vote queryset = TaggedItem.objects.get_by_model(qs, tag_instance) vote_attendence = [v.votes.all() for v in TaggedItem.objects.get_by_model(Vote, tag_instance)] d = {} for vote in vote_attendence: for v in vote: d[v] = d.get(v,0)+1 # now d is a dict: MK -> number of votes in this tag mks = d.keys() if mks: for mk in mks: mk.count = d[mk] average = float(sum([mk.count for mk in mks]))/len(mks) mks = [mk for mk in mks if mk.count>=average] mks = tagging.utils.calculate_cloud(mks) extra_context['members'] = mks if request.user.is_authenticated(): extra_context['watched_members'] = \ request.user.get_profile().members else: extra_context['watched_members'] = False return object_list(request, queryset, #return tagged_object_list(request, queryset_or_model=qs, tag=tag, template_name='laws/vote_list_by_tag.html', extra_context=extra_context)
def test_force_lowercase_tags(self): """ Test forcing tags to lowercase. """ settings.FORCE_LOWERCASE_TAGS = True Tag.objects.update_tags(self.dead_parrot, "foO bAr Ter") tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 3) foo_tag = get_tag("foo") bar_tag = get_tag("bar") ter_tag = get_tag("ter") self.failUnless(foo_tag in tags) self.failUnless(bar_tag in tags) self.failUnless(ter_tag in tags) Tag.objects.update_tags(self.dead_parrot, "foO bAr baZ") tags = Tag.objects.get_for_object(self.dead_parrot) baz_tag = get_tag("baz") self.assertEquals(len(tags), 3) self.failUnless(bar_tag in tags) self.failUnless(baz_tag in tags) self.failUnless(foo_tag in tags) Tag.objects.add_tag(self.dead_parrot, "FOO") tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 3) self.failUnless(bar_tag in tags) self.failUnless(baz_tag in tags) self.failUnless(foo_tag in tags) Tag.objects.add_tag(self.dead_parrot, "Zip") tags = Tag.objects.get_for_object(self.dead_parrot) self.assertEquals(len(tags), 4) zip_tag = get_tag("zip") self.failUnless(bar_tag in tags) self.failUnless(baz_tag in tags) self.failUnless(foo_tag in tags) self.failUnless(zip_tag in tags) f1 = FormTest.objects.create() f1.tags = u"TEST5" f1.save() tags = Tag.objects.get_for_object(f1) test5_tag = get_tag("test5") self.assertEquals(len(tags), 1) self.failUnless(test5_tag in tags) self.assertEquals(f1.tags, u"test5")
def get_images_queryset(self): images = Image.objects.all() self.e_context = dict() if 'tag' in self.kwargs: tag_instance = get_tag(self.kwargs['tag']) if tag_instance is None: raise Http404(_('No Tag found matching "%s".') % self.kwargs['tag']) self.e_context['tag'] = tag_instance images = TaggedItem.objects.get_by_model(images, tag_instance) if 'username' in self.kwargs: user = get_object_or_404(**{'klass': User, username_field: self.kwargs['username']}) self.e_context['view_user'] = user images = images.filter(user=user) if 'album_id' in self.kwargs: album = get_object_or_404(Album, id=self.kwargs['album_id']) self.e_context['album'] = album images = images.filter(album=album) if (not album.is_public) and\ (self.request.user != album.user) and\ (not self.request.user.has_perm('imagestore.moderate_albums')): raise PermissionDenied return images
def get_context_data(self, tag, **kwargs): context = super(TagPageView, self).get_context_data(**kwargs) current_site = Site.objects.get_current() current_language_code = translation.get_language() tag_instance = get_tag(tag) if tag_instance is None: raise Http404(_('No Tag found matching "%s".') % tag) try: article = Article.get_for_object(tag_instance) except ArticleForObject.DoesNotExist: # Get or create root try: root_path = URLPath.root() except NoRootURL: root_path = URLPath.create_root(site=current_site) # Get current language namespace. E.g. "/fr" try: language_ns_path = URLPath.get_by_path("/%s" % current_language_code) except URLPath.DoesNotExist: language_ns_path = URLPath.create_article( parent=root_path, slug=current_language_code, site=current_site, title=current_language_code) # Get or create the article from django.template.defaultfilters import slugify tag_slug = slugify(tag_instance.name) try: article_path = URLPath.get_by_path( "/%s/%s" % (current_language_code, tag_slug)) except URLPath.DoesNotExist: article_path = URLPath.create_article(parent=language_ns_path, slug=tag_slug, site=current_site, title=tag_instance.name) # Get the wiki article itself article = article_path.article article.add_object_relation(tag_instance) context['article'] = article # XXX: site not taken in account context['tag'] = tag_instance context['related_tags'] = list( reversed( sorted( Tag.objects.related_for_model(tag_instance, I4pProject, counts=True), key=attrgetter('count'), )))[:15] # Get project sheets tagged with this tag XXX: site=site may # not be correct 4 Random projects with at least one picture. # It's not possible to mix distinct and order by random, so # use a trick hilighted_projects = TaggedItem.objects.get_by_model( I4pProject.objects.using_translations().filter( language_code=current_language_code, master__site=current_site, master__pictures__isnull=False).distinct(), tag_instance).distinct() context['picture_projects'] = random.sample( hilighted_projects, min(4, len(hilighted_projects))) # Mature projects mature_projects = TaggedItem.objects.get_by_model( I4pProject.objects.using_translations().filter( master__site=current_site, master__status__in=('WIP', 'END')).distinct(), tag_instance).distinct() context['num_mature_projects_projects_with_tag'] = len(mature_projects) context['mature_projects'] = random.sample( mature_projects, min(4, len(mature_projects))) # Starting projects starting_projects = TaggedItem.objects.get_by_model( I4pProject.objects.using_translations().filter( master__site=current_site, master__status__in=('IDEA', 'BEGIN')).distinct(), tag_instance).distinct() context['num_starting_projects_projects_with_tag'] = len( starting_projects) context['starting_projects'] = random.sample( starting_projects, min(4, len(starting_projects))) # New projects context['new_projects'] = TaggedItem.objects.get_by_model( I4pProject.objects.using_translations().filter( master__site=current_site, ).distinct(), tag_instance).order_by('-master__created')[:4] # Latest modifications context['modified_projects'] = TaggedItem.objects.get_by_model( I4pProject.objects.using_translations().filter( master__site=current_site, ).distinct(), tag_instance).order_by('-modified')[:4] # Related people # List is to force evaluation to avoid a sql bug in queryset combining later (project__in=projects) projects = list( TaggedItem.objects.get_by_model( I4pProject.objects.using_translations().filter( master__site=current_site, ).distinct(), tag_instance).all()) # While we're at it, let's count them for free context['num_projects_with_tag'] = len(projects) context['people'] = ProjectMember.objects.filter( project__in=projects).order_by('?')[:6] return context
def testNormalisedTagInput(self): cheese = Tag.objects.create(name='cheese') self.assertEqual(cheese, get_tag(cheese)) self.assertEqual(cheese, get_tag('cheese')) self.assertEqual(cheese, get_tag(cheese.id)) self.assertEqual(None, get_tag('mouse'))
def get_queryset(self): self.tag = get_tag(self.kwargs['tag']) if self.tag is None: raise Http404("Matching tags not found".format(self.kwargs['tag'])) return TaggedItem.objects.get_by_model(ContentEntry.published.all(), self.tag)
def get_queryset(self): tag = settings.NEWSLETTER_TAG tag_instance = get_tag(tag) return TaggedItem.objects.get_by_model(Entry, tag_instance)
def filter_and_order(self, *args, **kwargs): stage = kwargs.get('stage', None) member = kwargs.get('member', None) pp_id = kwargs.get('pp_id', None) knesset_booklet = kwargs.get('knesset_booklet', None) gov_booklet = kwargs.get('gov_booklet', None) changed_after = kwargs.get('changed_after', None) changed_before = kwargs.get('changed_before', None) bill_type = kwargs.get('bill_type', 'all') knesset_id = kwargs.get('knesset_id', 'all') filter_kwargs = {} if stage and stage != 'all': if stage in BILL_AGRR_STAGES: qs = self.filter(BILL_AGRR_STAGES[stage]) else: filter_kwargs['stage__startswith'] = stage qs = self.filter(**filter_kwargs) else: qs = self.all() if knesset_id and knesset_id != 'all': knesset = Knesset.objects.get(number=int(knesset_id)) period_start = knesset.start_date period_end = knesset.end_date or date.today() if waffle.switch_is_active('use_old_statistics'): qs = qs.filter(stage_date__range=(period_start, period_end)) else: qs = self._filter_bills_by_proposal_date( member, period_end, period_start, qs) if kwargs.get('tagged', None): if kwargs['tagged'] == 'false': ct = ContentType.objects.get_for_model(Bill) filter_tagged = TaggedItem.objects.filter( content_type=ct).distinct().values_list('object_id', flat=True) qs = qs.exclude(id__in=filter_tagged) elif kwargs['tagged'] != 'all': qs = TaggedItem.objects.get_by_model(qs, get_tag(kwargs['tagged'])) if bill_type == 'government': qs = qs.exclude(gov_proposal=None) elif bill_type == 'knesset': qs = qs.exclude(knesset_proposal=None) elif bill_type == 'private': qs = qs.exclude(proposals=None) if pp_id: private_proposals = PrivateProposal.objects.filter( proposal_id=pp_id).values_list('id', flat=True) if private_proposals: qs = qs.filter(proposals__in=private_proposals) else: qs = qs.none() if knesset_booklet: knesset_proposals = KnessetProposal.objects.filter( booklet_number=knesset_booklet).values_list('id', flat=True) if knesset_proposals: qs = qs.filter(knesset_proposal__in=knesset_proposals) else: qs = qs.none() if gov_booklet: government_proposals = GovProposal.objects.filter( booklet_number=gov_booklet).values_list('id', flat=True) if government_proposals: qs = qs.filter(gov_proposal__in=government_proposals) else: qs = qs.none() if changed_after: qs = qs.filter(stage_date__gte=changed_after) if changed_before: qs = qs.filter(stage_date__lte=changed_before) return qs
def test_with_tag_instance(self): self.assertEquals(get_tag(self.cheese), self.cheese)
def test_nonexistent_tag(self): self.assertEquals(get_tag('mouse'), None)
def test_with_primary_key(self): self.assertEquals(get_tag(self.cheese.id), self.cheese)
def test_with_string(self): self.assertEquals(get_tag('cheese'), self.cheese)