Programmatically saving image to Django ImageField

Programmatically saving image to Django ImageField

Ok, I've tried about near everything and I cannot get this to work.

I have a Django model with an ImageField on it
I have code that downloads an image via HTTP (tested and works)
The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the ImageField)
All I need to do is associate the already existing image file path with the ImageField

I've written this code about 6 different ways.
The problem I'm running into is all of the code that I'm writing results in the following behavior:
(1) Django will make a 2nd file, (2) rename the new file, adding an _ to the end of the file name, then (3) not transfer any of the data over leaving it basically an empty re-named file.  What's left in the 'upload_to' path is 2 files, one that is the actual image, and one that is the name of the image,but is empty, and of course the ImageField path is set to the empty file that Django try to create.
In case that was unclear, I'll try to illustrate:
## Image generation code runs.... 
     generated_image.jpg     4kb

## Attempt to set the ImageField path...
     generated_image.jpg     4kb
     generated_image_.jpg    0kb

ImageField.Path = /Upload/generated_image_.jpg

How can I do this without having Django try to re-store the file?  What I'd really like is something to this effect...
model.ImageField.path = generated_image_path

...but of course that doesn't work.
And yes I've gone through the other questions here like this one as well as the django doc on File
After further testing, it only does this behavior when running under Apache on Windows Server.  While running under the 'runserver' on XP it does not execute this behavior. 
I am stumped.
Here is the code which runs successfully on XP...
f = open(thumb_path, 'r')
model.thumbnail = File(f)


Answer 1:

I have some code that fetches an image off the web and stores it in a model. The important bits are:

from django.core.files import File  # you need this somewhere
import urllib

# The following actually resides in a method of my model

result = urllib.urlretrieve(image_url) # image_url is a URL to an image

# is the ImageField
    File(open(result[0], 'rb'))

That’s a bit confusing because it’s pulled out of my model and a bit out of context, but the important parts are:

  • The image pulled from the web is not stored in the upload_to folder, it is instead stored as a tempfile by urllib.urlretrieve() and later discarded.
  • The method takes a filename (the os.path.basename bit) and a django.core.files.File object.

Let me know if you have questions or need clarification.

Edit: for the sake of clarity, here is the model (minus any required import statements):

class CachedImage(models.Model):
    url = models.CharField(max_length=255, unique=True)
    photo = models.ImageField(upload_to=photo_path, blank=True)

    def cache(self):
        """Store image locally if we have a URL"""

        if self.url and not
            result = urllib.urlretrieve(self.url)
                    File(open(result[0], 'rb'))

Answer 2:

Super easy if model hasn’t been created yet:

First, copy your image file to the upload path (assumed = ‘path/’ in following snippet).

Second, use something like:

class Layout(models.Model):
    image = models.ImageField('img', upload_to='path/')

layout = Layout()
layout.image = "path/image.png"

tested and working in django 1.4, it might work also for an existing model.

Answer 3:

Just a little remark. tvon answer works but, if you’re working on windows, you probably want to open() the file with 'rb'. Like this:

class CachedImage(models.Model):
    url = models.CharField(max_length=255, unique=True)
    photo = models.ImageField(upload_to=photo_path, blank=True)

    def cache(self):
        """Store image locally if we have a URL"""

        if self.url and not
            result = urllib.urlretrieve(self.url)
                    File(open(result[0], 'rb'))

or you’ll get your file truncated at the first 0x1A byte.

Answer 4:

Here is a method that works well and allows you to convert the file to a certain format as well (to avoid “cannot write mode P as JPEG” error):

import urllib2
from django.core.files.base import ContentFile
from PIL import Image
from StringIO import StringIO

def download_image(name, image, url):
    input_file = StringIO(urllib2.urlopen(url).read())
    output_file = StringIO()
    img =
    if img.mode != "RGB":
        img = img.convert("RGB"), "JPEG")".jpg", ContentFile(output_file.getvalue()), save=False)

where image is the django ImageField or your_model_instance.image
here is a usage example:

p = ProfilePhoto(user=user)
download_image(str(, p.image, image_url)

Hope this helps

Answer 5:

Ok, If all you need to do is associate the already existing image file path with the ImageField, then this solution may be helpfull:

from django.core.files.base import ContentFile

with open('/path/to/already/existing/file') as f:
  data =

# obj.image is the ImageField'imgfilename.jpg', ContentFile(data))

Well, if be earnest, the already existing image file will not be associated with the ImageField, but the copy of this file will be created in upload_to dir as ‘imgfilename.jpg’ and will be associated with the ImageField.

Answer 6:

What I did was to create my own storage that will just not save the file to the disk:

from import FileSystemStorage

class CustomStorage(FileSystemStorage):

    def _open(self, name, mode='rb'):
        return File(open(self.path(name), mode))

    def _save(self, name, content):
        # here, you should implement how the file is to be saved
        # like on other machines or something, and return the name of the file.
        # In our case, we just return the name, and disable any kind of save
        return name

    def get_available_name(self, name):
        return name

Then, in my models, for my ImageField, I’ve used the new custom storage:

from custom_storage import CustomStorage

custom_store = CustomStorage()

class Image(models.Model):
    thumb = models.ImageField(storage=custom_store, upload_to='/some/path')

Answer 7:

If you want to just “set” the actual filename, without incurring the overhead of loading and re-saving the file (!!), or resorting to using a charfield (!!!), you might want to try something like this —

model_instance.myfile = model_instance.myfile.field.attr_class(model_instance, model_instance.myfile.field, 'my-filename.jpg')

This will light up your model_instance.myfile.url and all the rest of them just as if you’d actually uploaded the file.

Like @t-stone says, what we really want, is to be able to set instance.myfile.path = ‘my-filename.jpg’, but Django doesn’t currently support that.

Answer 8:

THe simplest solution in my opinion:

from django.core.files import File

with open('path_to_file', 'r') as f:   # use 'rb' mode for python3
    data = File(f)'filename', data, True)

Answer 9:

This is might not be the answer you are looking for. but you can use charfield to store the path of the file instead of ImageFile. In that way you can programmatically associate uploaded image to field without recreating the file.

Answer 10:

You can try:

model.ImageField.path = os.path.join('/Upload', generated_image_path)

Answer 11:

class tweet_photos(models.Model):
upload_path='absolute path'
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 = self.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(tweet_photos, self).save()

Answer 12:

class Pin(models.Model):
    """Pin Class"""
    image_link = models.CharField(max_length=255, null=True, blank=True)
    image = models.ImageField(upload_to='images/', blank=True)
    title = models.CharField(max_length=255, null=True, blank=True)
    source_name = models.CharField(max_length=255, null=True, blank=True)
    source_link = models.CharField(max_length=255, null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    tags = models.ForeignKey(Tag, blank=True, null=True)

    def __unicode__(self):
        """Unicode class."""
        return unicode(self.image_link)

    def save(self, *args, **kwargs):
        """Store image locally if we have a URL"""
        if self.image_link and not self.image:
            result = urllib.urlretrieve(self.image_link)
  , File(open(result[0], 'r')))
            super(Pin, self).save()

Answer 13:

You can save image by using FileSystemStorage.
check the example below

def upload_pic(request):
if request.method == 'POST' and request.FILES['photo']:
    photo = request.FILES['photo']
    name = request.FILES['photo'].name
    fs = FileSystemStorage()
##### you can update file saving location too by adding line below #####
    fs.base_location = fs.base_location+'/company_coverphotos'
    filename =, photo)
    uploaded_file_url = fs.url(filename)+'/company_coverphotos'

Answer 14:

Your can use Django REST framework and python Requests library to Programmatically saving image to Django ImageField

Here is a Example:

import requests

def upload_image():
    url = ""

    data = {'first_name': "Rajiv", 'last_name': "Sharma"}

    photo = open('/path/to/photo'), 'rb')
    resume = open('/path/to/resume'), 'rb')
    files = {'photo': photo, 'resume': resume}

    request =, data=data, files=files)
    print(request.status_code, request.reason)