Friday, November 20, 2015

Saving image to Django's ImageField programmatically

In order to save an image to a Django model's ImageField programmatically instead of using the upload form, you can do as following example:

0. Assuming you have this model:

models.py
...

class MyModel(models.Model):
    image = models.ImageField(upload_to='path')
...

1. First, upload your image to the upload_to folder defined in your settings.py:

...
UPLOAD_TO = 'photos'
...


2. In views.py or any utility module:

from django.conf import settings
...

layout = MyModel()
layout.image = "%s/image.png" % settings.UPLOAD_TO
layout.save()




Reference: http://stackoverflow.com/questions/1308386/programmatically-saving-image-to-django-imagefield