1

My code currently lists all domains in a server using:

{% for domain in server.domain_set.all %}

I want to order the domains in the view by their url. Something like:

{% for domain in server.domain_set.all().order_by('url') %}

But I get an exception "could not parse the remainder". How can I order the list?

Burhan Khalid
  • 161,711
  • 18
  • 231
  • 272
Tom
  • 8,775
  • 24
  • 84
  • 144

2 Answers2

4

The "could not parse the remainder" errors is because you're including Python code in your django template. Django doesn't allow that.

You could add a method on the model:

def sorted_domains(self):
    return self.domain_set.all().order_by('url')

And then call it like this:

{% for domain in server.sorted_domains %}

An alternative is to set the default sort order on your Domain model with a Meta attribute.

Burhan Khalid
  • 161,711
  • 18
  • 231
  • 272
Reinout van Rees
  • 13,228
  • 2
  • 34
  • 67
3

You can use a dictsort filter:

Takes a list of dictionaries and returns that list sorted by the key given in the argument.

{% for domain in server.domain_set.all|dictsort:'url' %}

Also see:

Community
  • 1
  • 1
alecxe
  • 441,113
  • 110
  • 1,021
  • 1,148