Skip to content

Instantly share code, notes, and snippets.

@2ndmouse
Created March 31, 2014 04:49
Show Gist options
  • Save 2ndmouse/9885489 to your computer and use it in GitHub Desktop.
Save 2ndmouse/9885489 to your computer and use it in GitHub Desktop.
Django save uploaded file to disk
from django.core.files.temp import NamedTemporaryFile
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
# if you actually need the file
class MyMixin(object):
def pre_save(self, obj):
default_storage.save('/Users/2ndmouse/code/media/a.jpg', ContentFile(self.request.FILES['image'].read()))
# download online file and save it to image field
import urllib2
from urlparse import urlparse
class DownloadOnlineFileMixin(object):
def pre_save(self, obj):
imgUrl = 'https://avatars1.githubusercontent.com/u/6585995?s=140'
tmpImg = NamedTemporaryFile(delete=True) # automatically delete the file once it is closed
tmpImg.write(urllib2.urlopen(imgUrl).read())
tmpImg.flush() # prevent file truncate
o = urlparse(imgUrl)
filename = basename(o.path)
imgFile = File(tmpImg)
obj.image.save(filename, imgFile) # save the file into image field
# doing something cool with the image her ...
tmpImg.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment