I recently ran into the following problem: I needed to be able to display a list of users in a table that had a maximum of X columns. Since I could not find the solution on the Internet I decided to give it a try and here is my resulting template filter to do it:
def tablecols(data, cols):
rows = []
row = []
index = 0
for user in data:
row.append(user)
index = index + 1
if index % cols == 0:
rows.append(row)
row = []
# Still stuff missing?
if len(row) > 0:
rows.append(row)
return rows
register.filter_function(tablecols)
Then you can use it in your templates like so:
<table>
{% for row in members|tablecols:5 %}
<tr>
{% for member in row %}
<td>
{% show_simple_profile member user %}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
It will break down the “members” list into a list of lists, each of the first being a group of (in this case) 5 users max.
Have fun
Related:
- [Django] Dynamic redirection after login Here’s how to redirect to the login page in django,...
- Django: Reverse HTTP redirect with parameters Here’s how to, from a view, redirect to another URL...






Fantastic, thank you
No worries
Yay! Just what I needed. Thanks.
Oh – except for the last line, which should be:
register.filter('tablecols', tablecols)
Actually it works on my environment without the name. I think Django reverts to the function name if you don't provide one
Thanks much, works perfectly. And this is WAY cleaner and shorter than the example shown in the Django Wiki : http://code.djangoproject.com/wiki/ColumnizeTag
No problem