diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py index 9eabb6dd60..f93e799535 100644 --- a/django/template/defaultfilters.py +++ b/django/template/defaultfilters.py @@ -7,7 +7,7 @@ from decimal import Decimal, InvalidOperation, Context, ROUND_HALF_UP from functools import wraps from pprint import pformat -from django.template.base import Variable, Library +from django.template.base import Variable, Library, VariableDoesNotExist from django.conf import settings from django.utils import formats from django.utils.dateformat import format, time_format @@ -490,7 +490,10 @@ def dictsort(value, arg): Takes a list of dicts, returns that list sorted by the property given in the argument. """ - return sorted(value, key=Variable(arg).resolve) + try: + return sorted(value, key=Variable(arg).resolve) + except (TypeError, VariableDoesNotExist): + return u'' @register.filter(is_safe=False) def dictsortreversed(value, arg): @@ -498,7 +501,10 @@ def dictsortreversed(value, arg): Takes a list of dicts, returns that list sorted in reverse order by the property given in the argument. """ - return sorted(value, key=Variable(arg).resolve, reverse=True) + try: + return sorted(value, key=Variable(arg).resolve, reverse=True) + except (TypeError, VariableDoesNotExist): + return u'' @register.filter(is_safe=False) def first(value): diff --git a/tests/regressiontests/defaultfilters/tests.py b/tests/regressiontests/defaultfilters/tests.py index b44aa97704..94e8c43430 100644 --- a/tests/regressiontests/defaultfilters/tests.py +++ b/tests/regressiontests/defaultfilters/tests.py @@ -368,6 +368,13 @@ class DefaultFiltersTests(TestCase): [('age', 23), ('name', 'Barbara-Ann')], [('age', 63), ('name', 'Ra Ra Rasputin')]]) + # If it gets passed a list of something else different from + # dictionaries it should fail silently + self.assertEqual(dictsort([1, 2, 3], 'age'), '') + self.assertEqual(dictsort('Hello!', 'age'), '') + self.assertEqual(dictsort({'a': 1}, 'age'), '') + self.assertEqual(dictsort(1, 'age'), '') + def test_dictsortreversed(self): sorted_dicts = dictsortreversed([{'age': 23, 'name': 'Barbara-Ann'}, {'age': 63, 'name': 'Ra Ra Rasputin'}, @@ -379,6 +386,13 @@ class DefaultFiltersTests(TestCase): [('age', 23), ('name', 'Barbara-Ann')], [('age', 18), ('name', 'Jonny B Goode')]]) + # If it gets passed a list of something else different from + # dictionaries it should fail silently + self.assertEqual(dictsortreversed([1, 2, 3], 'age'), '') + self.assertEqual(dictsortreversed('Hello!', 'age'), '') + self.assertEqual(dictsortreversed({'a': 1}, 'age'), '') + self.assertEqual(dictsortreversed(1, 'age'), '') + def test_first(self): self.assertEqual(first([0,1,2]), 0) self.assertEqual(first(u''), u'')