Browse Source

Fixed #13809 -- Made FieldFile.open() respect its mode argument.

Chris Sinchok 8 years ago
parent
commit
ac1975b18b
2 changed files with 14 additions and 1 deletions
  1. 4 1
      django/db/models/fields/files.py
  2. 10 0
      tests/file_storage/tests.py

+ 4 - 1
django/db/models/fields/files.py

@@ -79,7 +79,10 @@ class FieldFile(File):
 
     def open(self, mode='rb'):
         self._require_file()
-        self.file.open(mode)
+        if hasattr(self, '_file') and self._file is not None:
+            self.file.open(mode)
+        else:
+            self.file = self.storage.open(self.name, mode)
     # open() doesn't alter the file's contents, but it does reset the pointer
     open.alters_data = True
 

+ 10 - 0
tests/file_storage/tests.py

@@ -742,6 +742,16 @@ class FileFieldStorageTests(TestCase):
         self.assertEqual(list(obj.normal.chunks(chunk_size=2)), [b"co", b"nt", b"en", b"t"])
         obj.normal.close()
 
+    def test_filefield_write(self):
+        # Files can be written to.
+        obj = Storage.objects.create(normal=SimpleUploadedFile('rewritten.txt', b'content'))
+        with obj.normal as normal:
+            normal.open('wb')
+            normal.write(b'updated')
+        obj.refresh_from_db()
+        self.assertEqual(obj.normal.read(), b'updated')
+        obj.normal.close()
+
     def test_filefield_reopen(self):
         obj = Storage.objects.create(normal=SimpleUploadedFile('reopen.txt', b'content'))
         with obj.normal as normal: