Login

Save an image to ImageField from URL

Author:
ekinertac
Posted:
October 27, 2012
Language:
Python
Version:
1.4
Tags:
image urls url imagefield urlparse
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()

More like this

  1. save image from url to django ImageField by kriwil 3 years, 4 months ago
  2. Updated Filter to resize a ImageField on demand (ver.2) by rawjam 5 years, 1 month ago
  3. get and image object by grillermo 3 years ago
  4. Filter to resize a ImageField on demand by michelts 7 years, 10 months ago
  5. ImageField with specified maximum image size by virhilo 4 years, 11 months ago

Comments

aaloy (on October 28, 2012):

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.