﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
15583	Sorting dict by keys within django template	Cal Leeming	nobody	"Currently, there is no way to sort a dict by its keys within a django template without doing mods within the view. This really should just work out of the box.

Test case:
{{{#!python
{'a': 'value 1',
 'c': 'value 3',
 'b': 'value 2',
}
{% for key, val in dict.items|sort %}
key: {{key}} / {{value}}
{% endfor %}
}}}
Current functionality:
{{{#!python
key: a / value 1
key: c / value 3
key: b / value 2
}}}


Functionality with sort patch:
{{{#!python
key: a / value 1
key: b / value 2
key: c / value 3
}}}

Someone has already written the appropriate code to do this (as a custom filter), and seems to work fine. I'd like to see this taken up for consideration to be put merged into the core, so you can use this filter without needing to put it in via custom template tags.

Sadly, I haven't got time to write the necessary core changes, test it, and submit as a patch file. If I get a chance before anyone else does, I'll get this done.

{{{#!python
#File: custom_filters.py
# Author: http://cookingupawebsiteindjango.blogspot.com/2009/05/custom-template-filters-manipulating.html
from django import template
from django.utils.datastructures import SortedDict

register = template.Library()

@register.filter(name='sort')
def listsort(value):
  if isinstance(value,dict):
    new_dict = SortedDict()
    key_list = value.keys()
    key_list.sort()
    for key in key_list:
      new_dict[key] = value[key]
    return new_dict
  elif isinstance(value, list):
    new_list = list(value)
    new_list.sort()
    return new_list
  else:
    return value
listsort.is_safe = True
}}}"	Uncategorized	closed	Template system	1.2	Normal	wontfix	sort, dict, keys, template, sorting, sorted, dictionary		Unreviewed	0	0	0	0	0	0
