Save an image to ImageField from URL
Author:
ekinertac
Posted:
October 27, 2012
Language:
Python
Version:
1.4
Score:
3 (after 3 ratings)
this is the right and working way
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 class Product ( models . Model ):
upload_path = 'media/product'
image = models . ImageField ( upload_to = upload_path , null = True , blank = True )
image_url = models . URLField ( null = True , blank = True )
def save ( self , * args , ** kwargs ):
if self . image_url :
import urllib , os
from urlparse import urlparse
file_save_dir = upload_path
filename = urlparse ( self . image_url ) . path . split ( '/' )[ - 1 ]
urllib . urlretrieve ( self . image_url , os . path . join ( file_save_dir , filename ))
self . image = os . path . join ( file_save_dir , filename )
self . image_url = ''
super ( Product , self ) . save ()
Comments
I could be a problem if the total length of the filename + path is greater than 100 (the default length). So it would be better if we force a maximum length on the self.image name.
#
Please login first before commenting.