From 7d0e56620882c207998a41ac07ec5da572045b31 Mon Sep 17 00:00:00 2001 From: David Sanders Date: Wed, 26 Apr 2023 22:17:57 +1000 Subject: [PATCH] Fixed #34518 -- Fixed crash of random() template filter with an empty list. --- django/template/defaultfilters.py | 5 ++++- tests/template_tests/filter_tests/test_random.py | 5 +++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py index d446b54ade..03676533b7 100644 --- a/django/template/defaultfilters.py +++ b/django/template/defaultfilters.py @@ -628,7 +628,10 @@ def length_is(value, arg): @register.filter(is_safe=True) def random(value): """Return a random item from the list.""" - return random_module.choice(value) + try: + return random_module.choice(value) + except IndexError: + return "" @register.filter("slice", is_safe=True) diff --git a/tests/template_tests/filter_tests/test_random.py b/tests/template_tests/filter_tests/test_random.py index 785f2d6a2f..8f197e6f13 100644 --- a/tests/template_tests/filter_tests/test_random.py +++ b/tests/template_tests/filter_tests/test_random.py @@ -24,3 +24,8 @@ class RandomTests(SimpleTestCase): "random02", {"a": ["a&b", "a&b"], "b": [mark_safe("a&b"), mark_safe("a&b")]} ) self.assertEqual(output, "a&b a&b") + + @setup({"empty_list": "{{ list|random }}"}) + def test_empty_list(self): + output = self.engine.render_to_string("empty_list", {"list": []}) + self.assertEqual(output, "")