Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / templatetags / filters.py @ 27e51b28

History | View | Annotate | Download (5.2 kB)

1
# Copyright 2011-2012 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
import calendar
35
import datetime
36
import math
37

    
38
from collections import defaultdict
39

    
40
from django import template
41
from django.core.paginator import Paginator, EmptyPage
42
from django.db.models.query import QuerySet
43

    
44
from synnefo.lib.ordereddict import OrderedDict
45

    
46
from astakos.im import settings
47
from astakos.im.models import ProjectResourceGrant
48

    
49
register = template.Library()
50

    
51
DELIM = ','
52

    
53

    
54
@register.filter
55
def monthssince(joined_date):
56
    now = datetime.datetime.now()
57
    date = datetime.datetime(
58
        year=joined_date.year, month=joined_date.month, day=1)
59
    months = []
60

    
61
    month = date.month
62
    year = date.year
63
    timestamp = calendar.timegm(date.utctimetuple())
64

    
65
    while date < now:
66
        months.append((year, month, timestamp))
67

    
68
        if date.month < 12:
69
            month = date.month + 1
70
            year = date.year
71
        else:
72
            month = 1
73
            year = date.year + 1
74

    
75
        date = datetime.datetime(year=year, month=month, day=1)
76
        timestamp = calendar.timegm(date.utctimetuple())
77

    
78
    return months
79

    
80

    
81
@register.filter
82
def to_unicode(s):
83
    return unicode(s)
84

    
85

    
86
@register.filter
87
def to_string(s):
88
    return str(s)
89

    
90

    
91
@register.filter
92
def lookup(d, key):
93
    try:
94
        return d.get(key)
95
    except:
96
        return
97

    
98

    
99
@register.filter
100
def lookup_uni(d, key):
101
    return d.get(unicode(key))
102

    
103

    
104
@register.filter
105
def dkeys(d):
106
    return d.keys()
107

    
108

    
109
@register.filter
110
def month_name(month_number):
111
    return calendar.month_name[month_number]
112

    
113

    
114
@register.filter
115
def todate(value, arg=''):
116
    secs = int(value) / 1000
117
    return datetime.datetime.fromtimestamp(secs)
118

    
119

    
120
# @register.filter
121
# def rcut(value, chars='/'):
122
#     return value.rstrip(chars)
123

    
124

    
125
@register.filter
126
def paginate(l, args):
127
    l = l or []
128
    page, delim, sorting = args.partition(DELIM)
129
    if sorting:
130
        if isinstance(l, QuerySet):
131
            l = l.order_by(sorting)
132
        elif isinstance(l, list):
133
            default = ''
134
            if sorting.endswith('_date'):
135
                default = datetime.datetime.utcfromtimestamp(0)
136
            l.sort(key=lambda i: getattr(i, sorting)
137
                   if getattr(i, sorting) else default)
138
    paginator = Paginator(l, settings.PAGINATE_BY)
139
    try:
140
        paginator.len
141
    except AttributeError:
142
        paginator._count = len(list(l))
143

    
144
    try:
145
        page_number = int(page)
146
    except ValueError:
147
        if page == 'last':
148
            page_number = paginator.num_pages
149
        else:
150
            page_number = 1
151
    try:
152
        page = paginator.page(page_number)
153
    except EmptyPage:
154
        page = paginator.page(1)
155
    return page
156

    
157

    
158
@register.filter
159
def concat(str1, str2):
160
    if not str2:
161
        return str(str1)
162
    return '%s%s%s' % (str1, DELIM, str2)
163

    
164

    
165
@register.filter
166
def items(d):
167
    if isinstance(d, defaultdict):
168
        return d.iteritems()
169
    return d
170

    
171

    
172
@register.filter
173
def get_value_after_dot(value):
174
    return value.split(".")[1]
175

    
176
# @register.filter
177
# def strip_http(value):
178
#     return value.replace('http://','')[:-1]
179

    
180

    
181
@register.filter
182
def truncatename(v, max=18, append="..."):
183
    length = len(v)
184
    if length > max:
185
        return v[:max] + append
186
    else:
187
        return v
188

    
189

    
190
@register.filter
191
def resource_groups(project_definition):
192
    try:
193
        grants = project_definition.projectresourcegrant_set
194
        return grants.values_list('resource__group', flat=True)
195
    except:
196
        return ()
197

    
198

    
199
@register.filter
200
def resource_grants(project_definition):
201
    try:
202
        grants = project_definition.projectresourcegrant_set
203
        grants = grants.values_list(
204
            'resource__name',
205
            'member_capacity'
206
        )
207
        return dict((e[0], e[1]) for e in grants)
208
    except:
209
        return {}