""" Helpers to deal with tags """ __revision__ = "$Rev$" __date__ = "$Date$" from django import template from django.conf import settings from django.core.cache import cache from zilbo.common.tag.models import Tag, TagObject from zilbo.common.utils.misc import get_content_type_id #from django.contrib.contenttypes.models import ContentType register = template.Library() class tagsfor_class(template.Node): """ return a object reference to a given object """ def __init__(self, obj, user_obj, summary_obj): self.object_name= obj self.user_obj = user_obj self.summary_obj = summary_obj def render(self, context): object = template.resolve_variable( self.object_name, context ) c_obj_id = get_content_type_id( object ) (u,s)= Tag.get_tags_for(c_obj_id, object.id ) context[self.user_obj] = u context[self.summary_obj] = s return "" def tagsfor(parser, token): """ {% tagsfor [as] user summmary %} """ bits = token.contents.split() tok="" if len(bits) > 5: raise template.TemplateSyntaxError, "'tagsfor' statements must be 'tagsfor as ': %s" % token.contents if len(bits) == 3: tok = bits[1] u = bits[2] s = bits[3] else: tok = bits[1] u = bits[3] s = bits[4] return tagsfor_class(tok,u,s) class TopTagsNodeObject(template.Node): """ what is the root of this application """ def __init__(self, objectname ): self.obj = objectname def render(self, context): object = template.resolve_variable( self.obj, context ) if object is None: return "" # ct = ContentType.objects.get_for_model( object ) c_obj_id = get_content_type_id( object ) # try: x = cache.get( "toptags_tag_%s_%s" % (settings.SITE_ID, c_obj_id )) x={} if x is None: summary = TagObject.objects.filter( site__id__exact = settings.SITE_ID, content_type__id__exact = c_obj_id ).order_by('weight')[:40] for i in summary: x[ i.tag.name ] =1 cache.set( "toptags_tag_%s_%s" % (settings.SITE_ID, c_obj_id) , x, 600 ) return " ".join( x.keys() ) class TopTagsNodeUser(template.Node): """ what is the root of this application """ def render(self, context): user = context.get('user', None) if user.is_anonymous(): return "" return "

User Prefs

  • "+str(user)+"
" def top_tags_user(parser, token): """ {% top_tags_user %} """ return TopTagsNodeUser() def top_tags_object(parser, token): """ {% top_tags_object object %} """ bits = token.contents.split() if len(bits) != 2: raise template.TemplateSyntaxError, "'top_tags_object' must be 'top_tags_object '" return TopTagsNodeObject(bits[1]) register.tag('tagsfor', tagsfor) register.tag('top_tags_user', top_tags_user ) register.tag('top_tags_object', top_tags_object )