bcklutracker / bcklutracker /

from django.shortcuts import render_to_response
from django.conf import settings
from django.template import RequestContext
from django import template
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.contrib.admin.views.decorators import staff_member_required
import couchdb, simplejson

import math
from .db import database

def _fetch_doc(insert_id):
    Fetches the object associated with the given insert ID and returns it 
    as Document instance. If no such object could be found, it raises a 
    Http404 exception.
    result = database.view('main/by_insert_id', key=insert_id)
    if len(result) == 0:
        raise Http404()
    for row in result:
        return couchdb.Document(row.value)

def index(request):
    """The main tracker view."""
    view = request.user.is_staff and 'main/by_insert_id' or 'main/visible_by_insert_id'
    items_per_page = settings.ITEMS_PER_PAGE 
    if request.is_ajax():
        # Expect the $last parameter to indicate what item the user
        # saw last
        last_seen = int(request.GET['last'])
        data = database.view(view, endkey=last_seen+1, descending=True, 
        tmpl = template.loader.get_template('index_ajax.html')
        result = {
            'num_elements': len(data),
            'last_item': len(data) and data.rows[0].key or None,
            'content': tmpl.render(RequestContext(request, {
                'data': data,
                'new_elements': len(data),
        return HttpResponse(simplejson.dumps(result), mimetype='text/json')
    page_nr = int(request.GET.get('p', 1))
    offset = (page_nr-1) * items_per_page
    data = database.view(view, count=items_per_page, 
        skip=offset, descending=True)
    total_pages = int(math.ceil(data.total_rows / items_per_page))
    return render_to_response('index.html', RequestContext(request, {
        'last_item': len(data) and data.rows[0].key or None,
        'data': data, 
        'total_pages': total_pages,
        'page_nr': page_nr,
        'has_next_page': page_nr < total_pages,
        'has_previous_page': page_nr > 1,
        'next_page': page_nr+1,
        'previous_page': page_nr-1,
        'max_per_page': items_per_page,

def toggle(request, pk):
    Allows staff members to hide entries from the index.
    doc = _fetch_doc(int(pk))
    hidden = doc.get('hidden', False)
    if request.method == 'POST':
        doc['hidden'] = not(hidden)
        # If this is just an AJAX request, don't bother with an actual
        # redirect but instead just return an ok.
        if request.is_ajax():
            return HttpResponse('')
        return HttpResponseRedirect('/')
        return render_to_response('confirm_%s.html' % (hidden and 'show' or 'hide'), RequestContext(request, {'doc': doc}))