Login

Calculate Sum of Values in Django Templates

Author:
marcosthomazs
Posted:
June 2, 2015
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

This snippets generate the sum of the field values, for use in summary reports. More info in https://github.com/thomazs/django_templates_plus

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# coding = utf-8

"""
Package containing functions to support the templates.
@author Marcos Thomaz da Silva - [email protected]
"""

__author__ = 'Marcos Thomaz da Silva - [email protected]'

class Cel(object):
    """
    Class Helper used to store summaries
    """
    value = uval = None
    def __add__(self,val):
        if self.value:
            self.value = self.value +  val
        else:
            self.value = val
        self.uval = val
        return val
    def __str__(self):
        return self.uval
    def __unicode__(self):
        return self.uval
    @property
    def total(self):
        return self.value
    def reset(self):
        self.value = self.uval = None
        return self


class VirtualSummary(object):
    """
    Class to be instantiated in views and used within the templates.
    Usage (only in django templates):
        vs = VirtualSummary()
        
        {{ vs.<your_field_to_summary> }}  = Create a new virtual field to store the summary
        {{ vs.<your_field_to_summary>|add:<value_to_sum> }} = Use the fielter "add" 
                                                              to realize the sum.
        {{ vs.total__<your_field_to_summary> }} = returns the result of the sum
        {{ vs.reset__<your_field_to_summary> }} = reset the sum and 
                                                  return None. Used 
                                                  for realize summary 
                                                  in groups/subgroups
        
        
    Complete Example:
    ================================================
    
    class Sale(models.Model):
    
        product = models.ForeignKey(Product)
        quantity = models.IntegerField()
        value = models.DecimalField('Unitary Value', max_digits=7, decimal_places=2)
        
        @property
        def subtotal(self):
            return self.quantity * self.value
        
        def __unicode__(self):
            return self.product.name
    
    
    def myview(request):
        vtable = VirtualSummary()
        my_sales = Sale.objects.all()
        return render(request, 'your_template.html' , locals())
        
    
    ======= your_template.html =====
    <html>
        <body>
            <table>
                <thead>
                    <tr>
                        <th>Product</th>
                        <th>Quantity</th><!-- {{ vtable.qty }} -->
                        <th>Un.Value</th><!-- {{ vtable.unval }} -->
                        <th>Subtotal</th><!-- {{ vtable.subtot }} -->
                    </tr>
                </thead>
                <tbody>
                    {% for sale in my_sales %}
                    <tr>
                        <td>{{ sale.product }}</td>
                        <td>{{ vtable.qty|add:sale.quantity }}</td>
                        <td>{{ vtable.unval|add:sale.value }}</td>
                        <td>{{ vtable.subtot|add:sale.subtotal }}</td>
                    </tr>
                    {% endfor %}
                </tbody>
                <tfooter>
                    <tr>
                        <th>Total</th>
                        <th>{{ vtable.total__qty }}</th>                        
                        <th>{{ vtable.total__unval }}</th>                        
                        <th>{{ vtable.total__subtot }}</th>                        
                    </tr>
                </tfooter>
            </table>
        </body>
    </html>
    """
    
    __values = {}
    
    # TODO Another operations: Subtraction, Average and Median
    
    def __getattr__(self, name):
        if name[:2] == '__' :
            return super(VirtualSummary, self).__getattr__(name)
        elif '__' in name:
            data = name.split('__')
            if data[0] == 'total':
                return self.__values[data[1]].total
            elif data[0] == 'reset':
                return self.__values[data[1]].reset()
        if not (name in self.__values):
            self.__values[name] = Cel()
        return self.__values[name]

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.