Handles creation of `order_by` criteria based on GET parameters and provides context variables to be used when generating table header sort links which respect the current sort field and direction, reversing the direction when the same header is sorted by again.
Sample view:
from somewhere import SortHeaders
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
LIST_HEADERS = (
('Username', 'username'),
('First Name', 'first_name'),
('Last Name', 'last_name'),
('Email', None),
)
def user_list(request):
sort_headers = SortHeaders(request, LIST_HEADERS)
users = User.objects.order_by(sort_headers.get_order_by())
return render_to_response('users/user_list.html', {
'users': users,
'headers': list(sort_headers.headers()),
})
Sample template:
{% load my_tags %}
<table cellspacing="0">
<thead>
<tr>
{% table_header headers %}
</tr>
</thead>
<tbody>
{% for user in users %}<tr class="{% cycle odd,even %}">
<td><a href="{{ user.get_absolute_url|escape }}">{{ user.username|escape }}</a></td>
<td>{{ user.first_name|escape }}</td>
<td>{{ user.last_name|escape }}</td>
<td>{{ user.email|escape }}</td>
</tr>
{% endfor %}
</tbody>
</table>
Sample inclusion tag:
from django import template
def table_header(context, headers):
return {
'headers': headers,
}
register = template.Library()
register.inclusion_tag('table_header.html', takes_context=True)(table_header)
Sample inclusion tag template:
{% for header in headers %}<th{{ header.class_attr }}>
{% if header.sortable %}<a href="{{ header.url|escape }}">{% endif %}
{{ header.text }}
{% if header.sortable %}</a>{% endif %}
</th>{% endfor %}