Save an image to ImageField from URL

 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 2 years, 5 months ago
  2. Updated Filter to resize a ImageField on demand (ver.2) by rawjam 4 years, 2 months ago
  3. get and image object by grillermo 2 years, 1 month ago
  4. Filter to resize a ImageField on demand by michelts 7 years ago
  5. ImageField with specified maximum image size by virhilo 4 years, 1 month 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.

#

(Forgotten your password?)