<s> from django import template <EOL> from django . contrib . contenttypes . models import ContentType <EOL> from django . contrib . sites . models import Site <EOL> from django_counter . models import ViewCounter <EOL> def counter ( object ) : <EOL> ctype = ContentType . objects . get_for_model ( object ) <EOL> return { <EOL> '<STR_LIT>' : ctype , <EOL> '<STR_LIT:object>' : object , <EOL> '<STR_LIT>' : Site . objects . get_current ( ) } <EOL> register = template . Library ( ) <EOL> register . inclusion_tag ( '<STR_LIT>' ) ( counter ) <EOL> @ register . tag ( '<STR_LIT>' ) <EOL> def do_count ( parser , token ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> tag , tmp_for , package , obj , tmp_as , var = token . split_contents ( ) <EOL> if tmp_for != '<STR_LIT>' : raise ValueError <EOL> if tmp_as != '<STR_LIT>' : raise ValueError <EOL> app , model = package . split ( '<STR_LIT:.>' ) <EOL> except ValueError : <EOL> raise template . TemplateSyntaxError , "<STR_LIT>" <EOL> content_type = ContentType . objects . get ( app_label__exact = app , model__exact = model ) <EOL> return ViewCountNode ( content_type = content_type , obj = obj , var = var ) <EOL> class ViewCountNode ( template . Node ) : <EOL> def __init__ ( self , content_type , obj , var ) : <EOL> self . content_type = content_type <EOL> self . obj = obj <EOL> self . var = var <EOL> def render ( self , context ) : <EOL> if self . obj . isdigit ( ) : <EOL> object_id = self . obj <EOL> else : <EOL> try : <EOL> object_id = template . resolve_variable ( self . obj , context ) <EOL> except template . VariableDoesNotExist : <EOL> return '<STR_LIT>' <EOL> try : <EOL> count = ViewCounter . objects . get ( content_type = self . content_type , object_id = object_id ) . count <EOL> except ViewCounter . DoesNotExist : <EOL> count = <NUM_LIT:0> <EOL> context [ self . var ] = count <EOL> return '<STR_LIT>' </s>
