1. Jay Baird
  2. Ochs

Source

Ochs / news / templatetags / story_extras.py

import datetime

from django import template
from django.template import Context, loader

from cms.models import Page

from news.models import Story, Poll
from news.views import check_poll

register = template.Library()

@register.inclusion_tag('news/eyebrow_links.html')
def eyebrow_links():
    links = Story.objects.filter(breaking_news=True, publish_date__lte=datetime.datetime.now().replace(hour=0)).order_by('-publish_date')[:1]
    if links:
        breaking_news = True
    else:
        links = Story.objects.filter(eyebrow=True).order_by('-publish_date')[:3]
        breaking_news = False
    return {'links': links, 'breaking_news': breaking_news}

@register.inclusion_tag('news/categories.html')
def top_categories():
    categories = Page.objects.filter(parent__isnull=True, publisher_public__isnull=False).order_by('tree_id', 'lft')
    categories = [c for c in categories if c.get_title().lower() not in ['about', 'contact']]
    return {'categories': categories}

@register.inclusion_tag('news/categories.html')
def footer_categories():
    categories = Page.objects.filter(parent__isnull=True, publisher_public__isnull=False).order_by('tree_id', 'lft')
    return {'categories': categories}

@register.inclusion_tag('news/latest.html')
def latest_stories(section=None):
    if section:
        kwargs = {'section': section}
    else:
        kwargs = {}
    stories = Story.objects.filter(**kwargs).order_by('-publish_date')
    return {
        'section':section,
        'stories': stories
    }

@register.tag(name="polls")
def do_polls(parser, token):
    try:
        tag_name, story = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires a single argument, the parent story." % token.contents.split()[0]
    return PollNode(story)
    
class PollNode(template.Node):
    def __init__(self, story):
        self.story = template.Variable(story)
    
    def render(self, context):
        try:
            story = self.story.resolve(context)
            poll_results = []
            t = loader.get_template('news/poll.html')
            print story
            print Poll.objects.filter(story=story)
            for poll in Poll.objects.filter(story=story):
                check_poll(context['request'], poll)
                choices = poll.choice_set.all()
                total_votes = sum([c.votes for c in choices])
                for c in choices:
                    c.percentage = int((c.votes / float(total_votes)) * 100) if total_votes else 0
                c = Context({
                    'total_votes': total_votes,
                    'poll': poll,
                    'choices': choices,
                })
                poll_results.append(t.render(c))
            return '\n'.join(poll_results)
        except template.VariableDoesNotExist:
            return ''