tags:

views:

43

answers:

2

I read some of the other posts about this and some recommendations involved javascript and using other libraries. I did something quick by hand, but I'm new to Django and Python for that matter so I'm curious if this isn't a good way to do it.

HTML

 <table>
        <tr>
            <td><a href="?sort=to">To</a></td>
            <td><a href="?sort=date">Date</a></td>
            <td><a href="?sort=type">Type</a></td>
        </tr>
        {% for record in records %}
        <tr><td>{{record.to}}</td><td>{{record.date}}</td><td>{{record.type}}</td></tr>
        {% endfor %}
    </table>

View

headers = {'to':'asc',
         'date':'asc',
         'type':'asc',}

def table_view(request):
    sort = request.GET.get('sort')
    if sort is not None:
        if headers[sort] == "des":
            records = Record.objects.all().order_by(sort).reverse()
            headers[sort] = "asc"
        else:
            records = Record.objects.all().order_by(sort) 
            headers[sort] = "des"
    else:
        records = Record.objects.all()
    return render_to_response("table.html",{'user':request.user,'profile':request.user.get_profile(),'records':records})
A: 

Looks good to me. I'd suggest one minor refactoring in the view code:

headers = {'to':'asc',
         'date':'asc',
         'type':'asc',}

def table_view(request):
    sort = request.GET.get('sort')
    records = Record.objects.all()

    if sort is not None:
        records = records.order_by(sort)

        if headers[sort] == "des":
            records = records.reverse()
            headers[sort] = "asc"
        else:
            headers[sort] = "des"

    return render_to_response(...)
Manoj Govindan
A: 

My first port of call for sortable tables is usually sorttable.js ( http://www.kryogenix.org/code/browser/sorttable/ )

or sortable-table ( http://yoast.com/articles/sortable-table/ )

StephenPaulger