Login

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()

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 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.

#

Please login first before commenting.