django-tables2 doesn't sort
Asked Answered
P

1

7

can't get sorting working for a django-tables2 table.

class MyModel(models.Model):
    pid = models.AutoField('id',primary_key = True)
    name = models.CharField(max_length = 255,
                            help_text='The name')
def show_mymodels(request):
    """ the view """
    table = MyModelTable(MyModel.objects.all())
    return render(request,'mymodel.html',{'table':table})

class MyModelTable(tables.Table):
    class Meta:
        model = MyModel
        orderable = True

And mymodel.html looks as follows:

{% load render_table from django_tables2 %}
{% render_table table %}

This renders the table correct but nothing happens when clicking the columns in the browser. Other then the urld change http://127.0.0.1:8000/show_mymodel --> http://127.0.0.1:8000/show_mymodel?sort=name

What is it that I'm doing wrong?

Pilewort answered 4/7, 2012 at 14:13 Comment(0)
B
19

You need a RequestConfig object as explained in the tutorial:

Using RequestConfig automatically pulls values from request.GET and updates the table accordingly. This enables data ordering and pagination.


from django_tables2 import RequestConfig

def show_mymodels(request):
    table = MyModelTable(MyModel.objects.all())
    RequestConfig(request).configure(table)
    return render(request, 'mymodel.html', {'table': table})
Bazemore answered 4/7, 2012 at 17:22 Comment(7)
Brilliant! I have looked through the docs a couple of times but only under ordering. And I've used that Ordering-link just below where it is mentioned. I can't understand how I missed it.Pilewort
@Pilewort : the funny part is that I never used django-tables so far (but I'll certainly have a use for it in our new big project), just googled it and the answer was just here on the first page of the FineManual <g>.Bazemore
@bruna desthuilliers: Well if I at least could have sad that the coffee machine was broken or something, but I have no excuses. About tables2; I can't say I have used it a lot, which is pretty obvious, but what I've seen so far, is that it's neat and a really good tool!Pilewort
I am surprised that right now this is not included in the documentation. For me it solved my problem and now it works. It makes me think that they removed it because should be working by default, but is notPractitioner
@Practitioner did you check you were reading the doc for the same package version as the one you're using ? I often forget to check this myself and waste time with things seemingly "not working" :-sBazemore
thanks. best answer. I was searching for this.Baedeker
They have removed this hint from the actual tutorial (Jan. 2022)Wollis

© 2022 - 2024 — McMap. All rights reserved.