Created
March 31, 2014 04:49
Django save uploaded file to disk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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