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
  • 169,990
  • 18
  • 245
  • 284
Tom
  • 9,275
  • 25
  • 89
  • 147

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
  • 169,990
  • 18
  • 245
  • 284
Reinout van Rees
  • 13,486
  • 2
  • 36
  • 68
  • @BurhanKhalid agreed, I really like this more than doing this in the template. Much cleaner. – alecxe Sep 04 '14 at 06:24
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
  • 462,703
  • 120
  • 1,088
  • 1,195