This was a bit of a tricky one to figure out. The reason being we store our files not in the file system but using MogileFS, which required a custom Storage wrapper.
So our model looks a little something like this.
1.
class
Product(models.Model):
2.
# other fields
3.
image
=
models.FileField(storage
=
MogileFSStorage(), upload_to
=
'product_images'
)
And that's completely fine if we're using the admin to manually upload image files.
However, if we wanted to programmatically save an image using code... Where do we begin?
I'm glad to say that it's actually easier than expected.
01.
from
django.core.files
import
File
02.
from
django.core.files.temp
import
NamedTemporaryFile
03.
04.
product
=
Product()
05.
# set all your variables here
06.
product.save()
07.
08.
# Save image
09.
image_url
=
'http://whatever.com/image.jpg'
10.
img_temp
=
NamedTemporaryFile(delete
=
True
)
11.
img_temp.write(urlopen(image_url).read())
12.
img_temp.flush()
13.
14.
product.image.save(
"image_%s"
%
product.pk, File(img_temp))
15.
product.save()
And that's it! There's no need to worry about storage stuff because that's handled at the model declaration level.
This code should work fine for both FileField and ImageField.
Of course, how to access the file is completely up to you and out of the scope of this post.
It'll all makes sense once someone puts it into perspective for you!