From 98d8acf33fb923b7c8f1694c15033ca86e655100 Mon Sep 17 00:00:00 2001
From: Jacob Kaplan-Moss <jacob@jacobian.org>
Date: Tue, 5 Aug 2008 17:43:05 +0000
Subject: [PATCH] Fixed #7683: Try not to delete uploaded files before moving
 them, and don't wig out of someone else does. Patch from screeley and spaetz.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@8217 bcc190cf-cafb-0310-a4f2-bffc1f526a37
---
 django/core/files/uploadedfile.py | 14 ++++++++++++--
 django/db/models/base.py          |  2 +-
 2 files changed, 13 insertions(+), 3 deletions(-)

diff --git a/django/core/files/uploadedfile.py b/django/core/files/uploadedfile.py
index c498561c18..5e81e968cd 100644
--- a/django/core/files/uploadedfile.py
+++ b/django/core/files/uploadedfile.py
@@ -202,11 +202,21 @@ class TemporaryUploadedFile(UploadedFile):
     def read(self, *args):          return self._file.read(*args)
     def seek(self, offset):         return self._file.seek(offset)
     def write(self, s):             return self._file.write(s)
-    def close(self):                return self._file.close()
     def __iter__(self):             return iter(self._file)
     def readlines(self, size=None): return self._file.readlines(size)
     def xreadlines(self):           return self._file.xreadlines()
-
+    def close(self):
+        try:
+            return self._file.close()
+        except OSError, e:
+            if e.errno == 2:
+                # Means the file was moved or deleted before the tempfile could unlink it.
+                # Still sets self._file.close_called and calls self._file.file.close()
+                # before the exception
+                return
+            else: 
+                raise e
+        
 class InMemoryUploadedFile(UploadedFile):
     """
     A file uploaded into memory (i.e. stream-to-memory).
diff --git a/django/db/models/base.py b/django/db/models/base.py
index 7d7def3bad..6b7d4bc32c 100644
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -529,8 +529,8 @@ class Model(object):
         full_filename = self._get_FIELD_filename(field)
         if hasattr(raw_field, 'temporary_file_path'):
             # This file has a file path that we can move.
-            raw_field.close()
             file_move_safe(raw_field.temporary_file_path(), full_filename)
+            raw_field.close()
         else:
             # This is a normal uploadedfile that we can stream.
             fp = open(full_filename, 'wb')