Source

milton / views.py

from logging import getLogger

from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.xheaders import populate_xheaders
from django.http import HttpResponse, HttpResponseRedirect, Http404, ImproperlyConfigured
from django.template import loader, Context, RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.conf import settings
from django.contrib.sites.models import *

from milton.models import *

from tagging.models import Tag, TaggedItem
from tagging.utils import get_tag_list


logger = getLogger(__name__)

### Stories ###

def story_detail(request, section=None, year=None, month=None, day=None, slug=None):
    # Fetch a story
    try:
        if section == None:
            story = Story.published.get(
            	section = None,
                date_published__year = int(year),
                date_published__month = int(month),
                date_published__day = int(day),
                slug = slug
            )
        else:
            story = Story.published.get(
                section__slug = section,
                date_published__year = int(year),
                date_published__month = int(month),
                date_published__day = int(day),
                slug = slug
                )
    except Story.DoesNotExist, e:
        # No result?  404.
        raise Http404
    except Story.MultipleObjectsReturned, e:
        # If you don't have a unique section-date-slug combo for your section (or lack thereof) then this triggers.
        raise ImproperlyConfigured("Multiple objects exist for the specified section, date, and name.")
    
    # Prepare the template data
    context = {
        "title":  story.title,
        "object": story,
    }

    template_name = "story_detail.html"
    templates = []
    if section:
        templates.append("section/" + section + "/" + template_name)
    templates.append(template_name)

    response = render_to_response(templates, context, context_instance=RequestContext(request))
    populate_xheaders(request, response, Story, story.id)
    return response


def story_archive(request, section=None, year=None, month=None, day=None, teasers=None):
    if teasers == None:
        teasers = settings.ARCHIVES_SHOW_TEASERS_ONLY
    
    # If there's a section, try and load it then filter the stories by it
    try:
        if section and len(section):
            logger.debug("story_archive: fetching the section named %s" % (section,))
            section = Section.objects.get(slug=section)
        else:
            section = None
    except Section.DoesNotExist:
        raise Http404
    
    # Fetch a list of stories
    logger.debug("story_archive: fetching the list of stories")
    stories = Story.published.filter(section=section)
    if year:
        stories = stories.filter(date_published__year=int(year))
        if month:
            stories = stories.filter(date_published__month=int(month))
            if day:
                stories = stories.filter(date_published__day=int(day))
    
    # Paginate the results
    logger.debug("story_archive: paginating the list of stories")
    page = int(request.GET.get('page', 1))        # Requested page number
    paginator = Paginator(stories, settings.SP_PAGE_SIZE)
    
    try:
        stories_page = paginator.page(page)
    except (EmptyPage, InvalidPage):
        stories_page = paginator.page(paginator.num_pages)
    
    # Prepare the context
    context = {
        "options": {
            "teasers": teasers
        },
        "page": stories_page
    }
    
    if year and month and day:
        context['title'] = "%04d-%02d-%02d" % (int(year), int(month), int(day))
    elif year and month:
        context['title'] = "%04d-%02d" % (int(year), int(month))
    elif year:
        context['title'] = "%04d" % int(year)
    
    template_name = "story_archive.html"
    templates = []
    if section:
        templates.append("section/" + section.slug + "/" + template_name)
    templates.append(template_name)
    
    logger.debug("story_archive: generating response")
    return render_to_response(templates, context, context_instance=RequestContext(request))


def view_page(request, url):
    # URLs begin with a slash, but a bad admin or urls.py can remove it.
    if not url.startswith('/'):
        url = "/" + url

    try:
        page = Page.published.get(url__exact=url, sites__id__exact=settings.SITE_ID)
    
    except Page.DoesNotExist, e:
        raise Http404
    
    except Page.MultipleObjectsReturned, e:
        raise Http404 #What else to do?  You broke it, man.  One URL = One Object.

    # Prepare the context
    context = {
        "title":  page.title,
        "object": page,
        "flatpage": page, #Let people use the same template to a degree
    }

    # Create the template list
    if page.template_name:
        templates = [page.template_name, "page.html"]
    else:
        templates = ["page.html"]

    response = render_to_response(templates, context, context_instance=RequestContext(request))
    populate_xheaders(request, response, Page, page.id)
    return response

def view_tag(request, tagname, teasers=True):
    tags = get_tag_list(tagname)
    if tags.count() == 0:
        raise Http404
    
    items = TaggedItem.objects.get_intersection_by_model(Story, tags)
    
    # Paginate the results
    page = int(request.GET.get('page', 1))        # Requested page number
    paginator = Paginator(items.select_related(depth=2), settings.SP_PAGE_SIZE)
    
    try:
        stories_page = paginator.page(page)
    except (EmptyPage, InvalidPage):
        stories_page = paginator.page(paginator.num_pages)
    
    context = {
        "title": "Stories tagged %s" % tagname,
        "options": {
            "teasers": teasers
        },
        "page": stories_page,
    }
    
    response = render_to_response("story_archive.html", context, context_instance=RequestContext(request))
    return response