moadeep
moadeep

Reputation: 4098

Dual Sortable table columns in django

I have found a partial solution to my problem - sorting table in django (Sortable table columns in django)

I am writing a task manager app. Here is part of the model

class Item(models.Model):
    author = models.ForeignKey(User)
    name = models.CharField('Brief summary of job', max_length=200)
    created = models.DateTimeField('Created', auto_now=True,auto_now_add=True)
    description = models.TextField('Description of job')

I have an index page where I want to store all jobs in a sortable table. Here is the function in views

def index(request):
    order_by = request.GET.get('order_by', 'deadline')
    jobs_list = Item.objects.all().order_by(order_by)
    context = {'jobs_list': jobs_list}
    return render(request, 'nc_jobs/index.html',context)

and the html template for the table

<table class="table table-striped table-bordered">
    <th><a href="?order_by=name">Name</a></th>
    <th><a href="?order_by=author">From</a></th>
    <th><a href="?order_by=job_for">FAO</a></th>
    <th><a href="?order_by=priority">Priority</a></th>
    <th><a href="?order_by=deadline">Deadline</a></th>
    <th><a href="?order_by=progress">Progress</a></th>
    <th><a href="?order_by=done">Done</a></th>
    {% for item in jobs_list %}
    <tr>
       <td><a href="/nc_jobs/{{ item.id }}/">{{ item.name }}</a></td>
       <td> {{ item.author }} </td>
       <td> {{ item.job_for }} </td>
       <td> {{ item.priority }} </td>
       <td> {{ item.deadline }} </td>
       <td> ...

Is there a way I can edit this code so that upon a second click of the table header I can sort any column in reverse order. And If I click this column header again it will resort in default order?

Thanks

Upvotes: 1

Views: 1338

Answers (1)

Aamir Rind
Aamir Rind

Reputation: 39659

I have used django-sorting in past, and it is good for your need. It will provide both ascending and descending ordering for a column.

{% load sorting_tags %}
{% anchor name "Name" %}
{% anchor author "From" %}
{% autosort jobs_list %}

Upvotes: 2

Related Questions