Code

Ticket #10044: 10044.diff

File 10044.diff, 4.8 KB (added by Gulopine, 5 years ago)

Updated FieldFile to accept File objects through attribute assignment, saving them automatically when the associated instance is saved

Line 
1Index: django/db/models/fields/files.py
2===================================================================
3--- django/db/models/fields/files.py    (revision 9756)
4+++ django/db/models/fields/files.py    (working copy)
5@@ -1,3 +1,4 @@
6+import copy
7 import datetime
8 import os
9 
10@@ -21,6 +22,7 @@
11         self.storage = field.storage
12         self._name = name or u''
13         self._closed = False
14+        self._committed = True
15 
16     def __eq__(self, other):
17         # Older code may be expecting FileField values to be simple strings.
18@@ -79,6 +81,7 @@
19 
20         # Update the filesize cache
21         self._size = len(content)
22+        self._committed = True
23 
24         # Save the object because it has changed, unless save is False
25         if save:
26@@ -100,6 +103,7 @@
27         # Delete the filesize cache
28         if hasattr(self, '_size'):
29             del self._size
30+        self._committed = False
31 
32         if save:
33             self.instance.save()
34@@ -110,7 +114,7 @@
35         # it's attached to in order to work properly, but the only necessary
36         # data to be pickled is the file's name itself. Everything else will
37         # be restored later, by FileDescriptor below.
38-        return {'_name': self.name, '_closed': False}
39+        return {'_name': self.name, '_closed': False, '_committed': True}
40 
41 class FileDescriptor(object):
42     def __init__(self, field):
43@@ -120,10 +124,21 @@
44         if instance is None:
45             raise AttributeError, "%s can only be accessed from %s instances." % (self.field.name(self.owner.__name__))
46         file = instance.__dict__[self.field.name]
47-        if not isinstance(file, FieldFile):
48+        if isinstance(file, basestring) or file is None:
49             # Create a new instance of FieldFile, based on a given file name
50             instance.__dict__[self.field.name] = self.field.attr_class(instance, self.field, file)
51-        elif not hasattr(file, 'field'):
52+        elif isinstance(file, File) and not isinstance(file, FieldFile):
53+            # Other types of files may be assigned as well, but they need to
54+            # have the FieldFile interface added to them
55+            file_copy = copy.copy(file)
56+            file_copy.__class__ = type(file.__class__.__name__,
57+                                       (file.__class__, FieldFile), {})
58+            file_copy.instance = instance
59+            file_copy.field = self.field
60+            file_copy.storage = self.field.storage
61+            file_copy._committed = False
62+            instance.__dict__[self.field.name] = file_copy
63+        elif isinstance(file, FieldFile) and not hasattr(file, 'field'):
64             # The FieldFile was pickled, so some attributes need to be reset.
65             file.instance = instance
66             file.field = self.field
67@@ -164,6 +179,14 @@
68             return None
69         return unicode(value)
70 
71+    def pre_save(self, model_instance, add):
72+        "Returns field's value just before saving."
73+        file = super(FileField, self).pre_save(model_instance, add)
74+        if file and not file._committed:
75+            # Commit the file to storage prior to saving the model
76+            file.save(file.name, file, save=False)
77+        return file
78+
79     def contribute_to_class(self, cls, name):
80         super(FileField, self).contribute_to_class(cls, name)
81         setattr(cls, self.name, FileDescriptor(self))
82Index: django/core/files/base.py
83===================================================================
84--- django/core/files/base.py   (revision 9756)
85+++ django/core/files/base.py   (working copy)
86@@ -32,6 +32,8 @@
87         return self.size
88 
89     def _get_name(self):
90+        if not hasattr(self, '_name'):
91+            raise ValueError("This operation requires the file to have a name.")
92         return self._name
93     name = property(_get_name)
94 
95Index: tests/modeltests/files/models.py
96===================================================================
97--- tests/modeltests/files/models.py    (revision 9756)
98+++ tests/modeltests/files/models.py    (working copy)
99@@ -9,6 +9,7 @@
100 import tempfile
101 from django.db import models
102 from django.core.files.base import ContentFile
103+from django.core.files.uploadedfile import SimpleUploadedFile
104 from django.core.files.storage import FileSystemStorage
105 from django.core.cache import cache
106 
107@@ -54,6 +55,16 @@
108 >>> obj1.normal.read()
109 'content'
110 
111+# File objects can be assigned to FileField attributes,  but shouldn't get
112+# committed until the model it's attached to is saved.
113+
114+>>> obj1.normal = SimpleUploadedFile('assignment.txt', 'content')
115+>>> temp_storage.listdir('tests')
116+([], [u'default.txt', u'django_test.txt'])
117+>>> obj1.save()
118+>>> temp_storage.listdir('tests')
119+([], [u'assignment.txt', u'default.txt', u'django_test.txt'])
120+
121 # Files can be read in a little at a time, if necessary.
122 
123 >>> obj1.normal.open()