Custom Search

Tuesday, April 13, 2010

django template filter to group objects alphabetically based on title or name

django template filter to group objects alphabetically based on title or name

--------------filter

@register.filter
def group_by_file_name(object_list):
res ={}
for x in object_list:
r = re.search('^[a-zA-Z]',x.title)
if r:
key = r.group().lower()
if not res.has_key(key):
print "reg", key
res[key] = [x]
else:
res[key].append(x)

n = re.search('^[0-9_]',x.title)
if n:
print "reg", n.group()
if not res.has_key('#'):
res['#'] = [x]
else:
res['#'].append(x)

print "result dictionary", res
# converting dictionary to list of tuples, since template support only List.
l = []
for k,v in res.items():
l.append((k,v))
l.sort(cmp = lambda x, y: cmp(x, y))
print "output list", l
return l

--------------- template

{% for g in files.object_list|group_by_file_name %}
<h4 class="file-atoz"><span>{{g.0}}</span></h4>
{% for p in g.1%}
<div class="outer-block">
{% for v in p.files %}
{%ifequal forloop.counter 1%}
<div class="inner-block">
<h1><a href="{{v.file.url}}"> {{v.file.name|format_file_name}}</a></h1>
<p>{{p.description}}</p>
<span class="details"> by {{v.created_by|gen_short_name}} on {{v.created_on.date}}, ({{v.file.size|filesizeformat}})</span>
<a href="{% url project_file_add_new_version project.id p.id%}" class="">Upload a new version</a>
<a href="{% url project_file_edit project.id p.id v.id%}" class="edit">Edit</a>
<a href="{%url project_file_delete project.id p.id v.id%}" class="delete">Delete</a>
</div>
<ul>
{% else %}
<li>
<h1><a href="{{v.file.url}}"> {{v.file.name|format_file_name}}</a></h1>
<span class="details"> by {{v.created_by|gen_short_name}} on {{v.created_on.date}}, ({{v.file.size|filesizeformat}})</span>
<a href="{% url project_file_edit project.id p.id v.id%}" class="edit">Edit</a>
</li>
{%endifequal%}
{% endfor %}
</ul>
</div>
{%endfor%}
{% endfor %}

--------------
Output:
-------

#
--
2sam
6repo

A
--
att_file
art
actr

B
--
balact
beta
bstar

C
--
catrot
camels
copies

**************************************************************

No comments:

Post a Comment