diff --git a/django/db/models/fields/files.py b/django/db/models/fields/files.py index 0d83ef5d0f..b2c93227e7 100644 --- a/django/db/models/fields/files.py +++ b/django/db/models/fields/files.py @@ -293,7 +293,7 @@ class FileField(Field): file = super(FileField, self).pre_save(model_instance, add) if file and not file._committed: # Commit the file to storage prior to saving the model - file.save(file.name, file, save=False) + file.save(file.name, file.file, save=False) return file def contribute_to_class(self, cls, name, **kwargs): diff --git a/tests/model_fields/test_filefield.py b/tests/model_fields/test_filefield.py index 19d414161d..e67b6dd515 100644 --- a/tests/model_fields/test_filefield.py +++ b/tests/model_fields/test_filefield.py @@ -1,4 +1,10 @@ -from django.test import TestCase +import os +import sys +import unittest + +from django.core.files import temp +from django.core.files.uploadedfile import TemporaryUploadedFile +from django.test import TestCase, override_settings from .models import Document @@ -54,3 +60,16 @@ class FileFieldTests(TestCase): def test_defer(self): Document.objects.create(myfile='something.txt') self.assertEqual(Document.objects.defer('myfile')[0].myfile, 'something.txt') + + @unittest.skipIf(sys.platform.startswith('win'), "Windows doesn't support moving open files.") + # The file's source and destination must be on the same filesystem. + @override_settings(MEDIA_ROOT=temp.gettempdir()) + def test_move_temporary_file(self): + """ + The temporary uploaded file is moved rather than copied to the + destination. + """ + with TemporaryUploadedFile('something.txt', 'text/plain', 0, 'UTF-8') as tmp_file: + tmp_file_path = tmp_file.temporary_file_path() + Document.objects.create(myfile=tmp_file) + self.assertFalse(os.path.exists(tmp_file_path), 'Temporary file still exists')