Add NumberColumn for nicely formated numbers.
authorW. Trevor King <wking@drexel.edu>
Thu, 21 Jul 2011 19:13:16 +0000 (15:13 -0400)
committerW. Trevor King <wking@drexel.edu>
Thu, 21 Jul 2011 19:13:16 +0000 (15:13 -0400)
Also remove unused AttrAccessor.

example/data/static/style.css
insider/views.py

index 76b42793897508d47373e821066906fda8003e25..9c5fb3802d2d6bae63f71146256e70a4fc694a36 100644 (file)
@@ -89,4 +89,18 @@ thead tr:nth-child(odd) {
   background: #ccc;
 }
 
+span.number {
+  float: right;            /* so decimal points match up */
+  font-family: monospace;  /* so that n-place digits line up */
+  text-align: '.';  /* should work by itself, but browser support is bad */
+}
+
+span.positive {
+  color: green;
+}
+
+span.negative {
+  color: red;
+}
+
 /* </div id="content"> */
index 55b3748878c512fe08e51783a1dfa0ae9231c332..5f2031614493b4d04b5177dc9f20f1f4ae00511b 100644 (file)
@@ -1,4 +1,6 @@
+from decimal import Decimal, ROUND_DOWN
 from datetime import datetime, timedelta
+import re
 
 from django.core.urlresolvers import reverse
 from django.shortcuts import render_to_response
@@ -6,23 +8,49 @@ from django.template import RequestContext
 from django.utils.safestring import mark_safe
 from django.views.generic import ListView
 
-from django_tables2 import Table, LinkColumn
+from django_tables2 import Table, Column, LinkColumn
 from django_tables2.utils import A
 from django_tables2.views import SingleTableMixin
 
 from .models import Company, Person, Ticker, Transaction
 
 
-class AttrAccessor (object):
-    def __init__(self, attribute, attributes):
-        self._attribute = attribute
-        self._attributes = attributes
-    def resolve(self, context):
-        return {'year': 1000}
-        obj = getattr(context, self._attribute)
-        print(obj)
-        print(self._attributes)
-        return dict((a, getattr(obj, a)) for a in self._attributes)
+class NumberColumn(Column):
+    @staticmethod
+    def _format_integer(integer, sep=','):
+        """Pretty-print an integer at thousands, millions, etc.
+
+        >>> NumberColumn._format_integer(1234567)
+        '1,234,567'
+        >>> NumberColumn._format_integer(-123456)
+        '-123,456'
+        >>> NumberColumn._format_integer(1234567, sep=' ')
+        '1 234 567'
+        """
+        sign = ''
+        if integer < 0:
+            sign = '-'
+        string = '{:d}'.format(abs(integer))
+        return sign + sep.join(re.findall('(.{1,3})', string[::-1]))[::-1]
+
+    def render(self, value):
+        classes = ['number']
+        if value < 0:
+            classes.append('negative')
+        if value > 0:
+            classes.append('positive')
+        if isinstance(value, Decimal):
+            integer = int(value.quantize(Decimal('1.'), rounding=ROUND_DOWN))
+            decimal = int(abs(value - integer) * 100)
+            print value
+            value = '{}.{:02d}'.format(self._format_integer(integer), decimal)
+            print value
+        elif isinstance(value, int):
+            value = self._format_integer(value)
+        else:
+            raise NotImplementedError(type(value))
+        return mark_safe(u'<span class="{}">{}</span>'.format(
+                u' '.join(classes), value))
 
 
 class TransactionTable(Table):
@@ -32,6 +60,8 @@ class TransactionTable(Table):
         'date', kwargs=dict((x, A('date.{}'.format(x)))
                             for x in ['year', 'month', 'day']))
     ticker = LinkColumn('ticker', args=[A('ticker.pk')])
+    shares = NumberColumn()
+    value = NumberColumn()
 
     class Meta:
         model = Transaction