Skip to content

Commit 70f39e4

Browse files
smithdc1felixxm
authored andcommitted
Refs #30686 -- Fixed text truncation for negative or zero lengths.
1 parent 3e820d1 commit 70f39e4

File tree

3 files changed

+10
-2
lines changed

3 files changed

+10
-2
lines changed

django/utils/text.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,8 @@ def chars(self, num, truncate=None, html=False):
104104
"""
105105
self._setup()
106106
length = int(num)
107+
if length <= 0:
108+
return ""
107109
text = unicodedata.normalize("NFC", self._wrapped)
108110

109111
# Calculate the length to truncate to (max length - end_text length)
@@ -144,6 +146,8 @@ def words(self, num, truncate=None, html=False):
144146
"""
145147
self._setup()
146148
length = int(num)
149+
if length <= 0:
150+
return ""
147151
if html:
148152
return self._truncate_html(length, truncate, self._wrapped, length, True)
149153
return self._text_words(length, truncate)

tests/template_tests/filter_tests/test_truncatechars_html.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ def test_truncate_zero(self):
88
truncatechars_html(
99
'<p>one <a href="#">two - three <br>four</a> five</p>', 0
1010
),
11-
"",
11+
"",
1212
)
1313

1414
def test_truncate(self):

tests/utils_tests/test_text.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ def test_truncate_chars(self):
8989

9090
# Make a best effort to shorten to the desired length, but requesting
9191
# a length shorter than the ellipsis shouldn't break
92-
self.assertEqual("", text.Truncator("asdf").chars(0))
92+
self.assertEqual("...", text.Truncator("asdf").chars(1, truncate="..."))
9393
# lazy strings are handled correctly
9494
self.assertEqual(
9595
text.Truncator(lazystr("The quick brown fox")).chars(10), "The quick…"
@@ -123,6 +123,8 @@ def test_truncate_chars_html(self):
123123
"…",
124124
truncator.chars(1, html=True),
125125
)
126+
self.assertEqual("", truncator.chars(0, html=True))
127+
self.assertEqual("", truncator.chars(-1, html=True))
126128
self.assertEqual(
127129
'<p id="par"><strong><em>The qu....</em></strong></p>',
128130
truncator.chars(10, "....", html=True),
@@ -206,6 +208,8 @@ def test_truncate_words(self):
206208
lazystr("The quick brown fox jumped over the lazy dog.")
207209
)
208210
self.assertEqual("The quick brown fox…", truncator.words(4))
211+
self.assertEqual("", truncator.words(0))
212+
self.assertEqual("", truncator.words(-1))
209213

210214
def test_truncate_html_words(self):
211215
truncator = text.Truncator(

0 commit comments

Comments
 (0)