1
0
mirror of https://github.com/django/django.git synced 2025-01-03 06:55:47 +00:00

Fixed #34518 -- Fixed crash of random() template filter with an empty list.

This commit is contained in:
David Sanders 2023-04-26 22:17:57 +10:00 committed by GitHub
parent 18a7f2c711
commit 7d0e566208
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 9 additions and 1 deletions

View File

@ -628,7 +628,10 @@ def length_is(value, arg):
@register.filter(is_safe=True) @register.filter(is_safe=True)
def random(value): def random(value):
"""Return a random item from the list.""" """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) @register.filter("slice", is_safe=True)

View File

@ -24,3 +24,8 @@ class RandomTests(SimpleTestCase):
"random02", {"a": ["a&b", "a&b"], "b": [mark_safe("a&b"), mark_safe("a&b")]} "random02", {"a": ["a&b", "a&b"], "b": [mark_safe("a&b"), mark_safe("a&b")]}
) )
self.assertEqual(output, "a&b 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, "")