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:

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

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

UPLOAD_TO = 'photos'

2. In or any utility module:

from django.conf import settings

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