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. ResizeImageField by wim 2 years, 7 months ago
  2. save image from url to django ImageField by kriwil 1 year, 6 months ago
  3. ImageWithThumbsField by zenx 4 years, 5 months ago
  4. add port from settings file to an url by sebnapi 11 months, 1 week ago
  5. UPDATED: Django Image Thumbnail Filter by danfairs 5 years, 6 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.

#

stonan (on February 3, 2013):

I think user Aaloy has got a good point there.rahapelit

#

(Forgotten your password?)