Commits

Dan Watson committed 3a75445

Add pagination to stream views

Comments (0)

Files changed (8)

leaves/managers.py

 from django.db import models
 from django.conf import settings
-from leaves.utils import filter_active_leaves, get_leaf_classes
+from leaves.utils import filter_active_leaves, get_leaf_classes, get_site
 
 class RequestSiteManager (models.Manager):
 	"""
 	current request. This requires LeavesMiddleware.
 	"""
 	def get_query_set(self):
-		try:
-			from leaves.middleware import request_context
-			site_pk = request_context.site.pk
-		except:
-			site_pk = settings.SITE_ID
-		return super(RequestSiteManager, self).get_query_set().filter(sites__id=site_pk)
+		return super(RequestSiteManager, self).get_query_set().filter(sites=get_site())
 
 class LeafManager(RequestSiteManager):
 	"""
 				related += [c.__name__.lower() for c in get_leaf_classes()]
 			qs = qs.select_related(*related)
 		return qs
+
+	def stream(self, select_related=True):
+		site = get_site()
+		return self.active(select_related).filter(subclass__in=site.preferences.stream_types.all(), stream=True)
 from leaves.utils import load_translations
 import datetime
 import inspect
-import hashlib
 
 # Django comes with a list of languages it supports, so we use that. We build
 # our own TRANSLATED_LANGUAGES list so that the language names are translated in
 	objects = models.Manager()
 	on_site = LeafManager()
 
+	class Meta:
+		ordering = ('-pub_date', 'title')
+
 	def __unicode__(self):
 		return self.title
 
 	def __unicode__(self):
 		return self.key
 
-def attachment_checksum(f):
-	"""
-	Compute the md5 hash of the specified file. Adapted from:
-	http://thejaswihr.blogspot.com/2008/06/python-md5-checksum-of-file.html	
-	"""
-	try:
-		f.open(mode='rb')
-	except IOError:
-		return 'No md5 available.'
-	content = f.readlines()
-	f.close()
-	m = hashlib.md5()
-	for line in content:
-		m.update(line)
-	return m.hexdigest()
-
-def attachment_path(instance, filename):
-	return instance.leaf.pk
-
-class Attachment (models.Model, Translatable):
-	leaf = models.ForeignKey(Leaf, related_name='attachments')
-	attachment = models.FileField(upload_to=attachment_path)
-	filename = models.CharField(max_length=200)
-	title = models.CharField(max_length=200)
-	md5_checksum = models.CharField(max_length=32, editable=False) 
-	num_downloads = models.PositiveIntegerField(default=0, editable=False)
-	
-	def __unicode__(self):
-		return self.filename
-	
-	def save(self, **kwargs):
-		self.md5_checksum = attachment_checksum(self.attachment)
-		super(Leaf, self).save(**kwargs)
-
-	@models.permalink
-	def get_absolute_url(self):
-		return ('view-attachment', (), {'attachment_id': self.pk, 'filename': self.filename})
-
 class Comment (models.Model):
 	leaf = models.ForeignKey(Leaf, related_name='comments')
 	title = models.CharField(max_length=200, blank=True)

leaves/plugins/blog/views.py

 from django.conf import settings
 from leaves.plugins.blog.models import Post, Category
 from leaves.views import view_leaf
+from leaves.utils import get_page
 
 def view_post(request, year, month, day, slug):
 	post = get_object_or_404(Post.on_site.active(), pub_date__year=year, pub_date__month=month, pub_date__day=day, slug=slug)
 
 def view_category(request, slug):
 	cat = get_object_or_404(Category.on_site, slug=slug)
-	latest_matches = Post.on_site.active().filter(Q(categories=cat) | Q(categories__in=cat.descendants())).distinct()[:10]
+	posts = Post.on_site.active().filter(Q(categories=cat) | Q(categories__in=cat.descendants())).distinct()
 	return TemplateResponse(request, 'blog/category.html', {
-		'leaves': latest_matches,
+		'page': get_page(request, posts),
 		'category': cat,
 	})

leaves/templatetags/leaf.py

 from django.utils.importlib import import_module
 from django.conf import settings
 from leaves.models import Leaf, Comment
-from leaves.utils import format_text
+from leaves.utils import format_text, get_site
 import hashlib
 import urllib
 
 
 @register.inclusion_tag('leaf_dates.html')
 def leaf_dates(group='month', current=None):
-	dates = [d.date() for d in Leaf.objects.dates('pub_date', group, order='DESC')]
+	dates = [d.date() for d in Leaf.on_site.stream().dates('pub_date', group, order='DESC')]
 	return {
 		'dates': dates,
 		'group': group,

leaves/themes/stream/static/stream/css/style.css

 	top: 3px;
 }
 
+.pagination {
+    border-top: 1px dotted #ddd;
+    padding: 10px 0px;
+}
+.pagination a {
+    font-size: 1.3em;
+}
+.pagination .previous {
+    float: left;
+}
+.pagination .next {
+    float: right;
+}
+
 .leaf-header {
     font-size: 1.5em;
     font-weight: bold;

leaves/themes/stream/templates/index.html

 
 {% block content %}
 <div class="leaves">
-{% for leaf in leaves %}
+{% for leaf in page.object_list %}
     <div class="leaf-stream">
         {% leaf_summary leaf %}
     </div>
     <div class="leaf-stream">There are no leaves to display.</div>
 {% endfor %}
 </div>
+{% if page.has_other_pages %}
+<div class="pagination">
+    {% if page.has_previous %}
+    <a class="previous" href="?page={{ page.previous_page_number }}">&laquo; Newer</a>
+    {% endif %}
+    {% if page.has_next %}
+    <a class="next" href="?page={{ page.next_page_number }}">Older &raquo;</a>
+    {% endif %}
+    <div style="clear:both;"></div>
+</div>
+{% endif %}
 {% endblock %}
 from django.conf import settings
 from django.contrib.sites.models import Site
+from django.core.paginator import Paginator, InvalidPage, EmptyPage
 from django.db import models
 from django.utils.encoding import force_unicode
 from django.utils.safestring import mark_safe
 import os, datetime
 
 class PluginHelperProxy (object):
-	
+
 	def __init__(self):
 		self.base = importlib.import_module('leaves.helpers')
-	
+
 	def __getattr__(self, name):
 		if hasattr(self.base, name):
 			return getattr(self.base, name)
 		models.Q(**{'status': 'published'}),
 	)
 
+def get_page(request, queryset):
+	"""
+	Returns a django.core.pagination.Page object based on the page number
+	in the request, the stream_count preference for the site, and the specified
+	queryset.
+	"""
+	paginator = Paginator(queryset, request.site.preferences.stream_count)
+	try:
+		pagenum = int(request.GET.get('page', '1'))
+		if pagenum < 1:
+			pagenum = 1
+	except ValueError:
+		pagenum = 1
+	try:
+		page = paginator.page(pagenum)
+	except (EmptyPage, InvalidPage):
+		page = paginator.page(paginator.num_pages)
+	return page
+
 def get_leaf_classes():
 	"""
 	Returns a list of all installed Leaf subclasses.
 		theme_static += '/'
 	theme_static += request.site.preferences.theme + '/'
 	return {
-		'helpers': PluginHelperProxy(),
+		'leaves': PluginHelperProxy(),
 		'site': request.site,
 		'THEME_STATIC_URL': theme_static,
 		'None': None,
 from django.contrib import messages
 from django.contrib.auth.models import User
 from django.conf import settings
-from django.http import HttpResponse, Http404
+from django.http import Http404
 from leaves.models import Leaf, Tag
 from leaves.forms import CommentForm
-import datetime, mimetypes
+from leaves.utils import get_page
+import datetime
 
 def homepage(request):
 	mod_path, func_name = settings.LEAVES_HOMEPAGE_VIEW.rsplit('.', 1)
 	return view_func(request)
 
 def leaf_stream(request):
-	prefs = request.site.preferences
-	leaves = Leaf.on_site.active().filter(subclass__in=prefs.stream_types.all(), stream=True)
 	return TemplateResponse(request, 'index.html', {
-		'leaves': leaves.order_by('-pub_date')[:prefs.stream_count],
+		'page': get_page(request, Leaf.on_site.stream()),
 	})
 
 def view_archive(request, year, month=None):
 			month = int(month)
 	except:
 		raise Http404
-	prefs = request.site.preferences
-	leaves = Leaf.on_site.active().filter(subclass__in=prefs.stream_types.all(), stream=True, pub_date__year=year)
+	leaves = Leaf.on_site.stream().filter(pub_date__year=year)
 	current_date = datetime.date(year, 1, 1)
 	archive_type = 'year'
 	if month:
 		current_date = datetime.date(year, month, 1)
 		archive_type = 'month'
 	return TemplateResponse(request, 'archive.html', {
-		'leaves': leaves.order_by('-pub_date'),
+		'page': get_page(request, leaves),
 		'archive_type': archive_type,
 		'current_date': current_date,
 	})
 
-def view_attachment(request, attachment_id, filename):
-	attachment = get_object_or_404(Attachment, pk=attachment_id)
-	try:
-		f = attachment.attachment.open(mode='rb')
-		mime = mimetypes.guess_type(f.name)[0] 
-		data = f.read()
-		resp = HttpResponse(data, mimetype=mime)
-		if attachment.filename:
-			resp['Content-Disposition'] = 'inline; filename="%s"' % attachment.filename
-		elif attachment.title:
-			resp['Content-Disposition'] = 'inline; filename="%s"' % attachment.title
-		else:
-			resp['Content-Disposition'] = 'inline; filename="%d"' % attachment.pk
-		return resp
-	except Exception, ex:
-		return HttpResponse('')	
-
 def leaf_search(request):
-	prefs = request.site.preferences
-	leaves = Leaf.on_site.active().filter(subclass__in=prefs.stream_types.all(), stream=True)
+	leaves = Leaf.on_site.stream()
 	if 'q' in request.GET:
 		term = request.GET['q'].strip()
 		q = Q(title__icontains=term) | Q(content__icontains=term) | Q(summary__icontains=term)
 		leaves = leaves.filter(q)
 	return TemplateResponse(request, 'search.html', {
 		'q': request.GET.get('q', '').strip(),
-		'leaves': leaves.order_by('-pub_date')[:prefs.stream_count],
+		'page': get_page(request, leaves),
 	})
 
 def view_tag(request, slug):
-	prefs = request.site.preferences
 	tag = get_object_or_404(Tag.on_site, slug=slug)
-	leaves = Leaf.on_site.active().filter(tags=tag, subclass__in=prefs.stream_types.all(), stream=True)
+	leaves = Leaf.on_site.stream().filter(tags=tag)
 	return TemplateResponse(request, 'tag.html', {
-		'leaves': leaves.order_by('-pub_date'),
+		'page': get_page(request, leaves),
 		'tag': tag,
 	})
 
 def view_author(request, username):
-	prefs = request.site.preferences
 	author = get_object_or_404(User, username=username)
-	leaves = Leaf.on_site.active().filter(author_user=author, subclass__in=prefs.stream_types.all(), stream=True)
+	leaves = Leaf.on_site.stream().filter(author_user=author)
 	return TemplateResponse(request, 'author.html', {
-		'leaves': leaves.order_by('-pub_date'),
+		'page': get_page(request, leaves),
 		'author': author,
 	})