Skip to content

Commit a9d03c4

Browse files
gutardsarahboyce
authored andcommitted
[5.1.x] Fixed #36191 -- Truncated the overwritten file content in FileSystemStorage.
Backport of 0d1dd6b from main.
1 parent 20e965e commit a9d03c4

File tree

4 files changed

+19
-2
lines changed

4 files changed

+19
-2
lines changed

AUTHORS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,7 @@ answer newbie questions, and generally made Django that much better:
361361
Fraser Nevett <[email protected]>
362362
Gabriel Grant <[email protected]>
363363
Gabriel Hurley <[email protected]>
364+
Gaël Utard
364365
365366
Garry Lawrence
366367
Garry Polley <[email protected]>

django/core/files/storage/filesystem.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -129,11 +129,11 @@ def _save(self, name, content):
129129
)
130130
# RemovedInDjango60Warning: when the deprecation ends, replace with:
131131
# if self._allow_overwrite:
132-
# open_flags = open_flags & ~os.O_EXCL
132+
# open_flags = open_flags & ~os.O_EXCL | os.O_TRUNC
133133
if self.OS_OPEN_FLAGS != open_flags:
134134
open_flags = self.OS_OPEN_FLAGS
135135
elif self._allow_overwrite:
136-
open_flags = open_flags & ~os.O_EXCL
136+
open_flags = open_flags & ~os.O_EXCL | os.O_TRUNC
137137
fd = os.open(full_path, open_flags, 0o666)
138138
_file = None
139139
try:

docs/releases/5.1.7.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,7 @@ Bugfixes
1212
* Fixed a bug in Django 5.1 where the ``{% querystring %}`` template tag
1313
returned an empty string rather than ``"?"`` when all parameters had been
1414
removed from the query string (:ticket:`36182`).
15+
16+
* Fixed a bug in Django 5.1 where ``FileSystemStorage``, with
17+
``allow_overwrite`` set to ``True``, did not truncate the overwritten file
18+
content (:ticket:`36191`).

tests/file_storage/tests.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,18 @@ def test_save_overwrite_behavior(self):
704704
finally:
705705
self.storage.delete(name)
706706

707+
def test_save_overwrite_behavior_truncate(self):
708+
name = "test.file"
709+
original_content = b"content extra extra extra"
710+
new_smaller_content = b"content"
711+
self.storage.save(name, ContentFile(original_content))
712+
try:
713+
self.storage.save(name, ContentFile(new_smaller_content))
714+
with self.storage.open(name) as fp:
715+
self.assertEqual(fp.read(), new_smaller_content)
716+
finally:
717+
self.storage.delete(name)
718+
707719
def test_save_overwrite_behavior_temp_file(self):
708720
"""Saving to same file name twice overwrites the first file."""
709721
name = "test.file"

0 commit comments

Comments
 (0)