8

I have some model class with a filer.fields.image.FilerImageField as a field.

from filer.fields.image import FilerImageField
class ModelName(Model):
    icon = FilerImageField(null=True, blank=True)

How to programmatically create or fill an icon field if I have a local path to an image file?

Sergey
  • 425
  • 1
  • 4
  • 11

1 Answers1

20

You can approach it this way:

from django.contrib.auth.models import User
from django.core.files import File
from filer.models import Image

filename = 'file'
filepath = 'path/to/file'
user = User.objects.get(username='testuser')
with open(filepath, "rb") as f:
    file_obj = File(f, name=filename)
    image = Image.objects.create(owner=user,
                                 original_filename=filename,
                                 file=file_obj)
    instance = ModelName(icon=image)
    instance.save()

image is an instance of filer.models.Image, assign it to icon attribute of a Model instance, FilerImageField will handle it for you.

Flimm
  • 136,138
  • 45
  • 251
  • 267
iMom0
  • 12,493
  • 3
  • 49
  • 61
  • ValueError: Cannot assign "": "Course.icon" must be a "Image" instance. – Sergey Dec 17 '13 at 14:39
  • @user2120409 Oh, image must be an instance of `filer.models.Image`.I have updated my answer, try again please. – iMom0 Dec 17 '13 at 14:51
  • In python 3, we must explicitly say that the file is binary and write: `with open(filepath, 'rb') as f:`. – Philipp Zedler May 10 '16 at 15:44
  • Also, open `filepath` with `"rb"` mode as it is a binary file. – Geoffrey R. Jun 20 '16 at 20:25
  • Even in Python 2, @PhilippZedler , "rb" is required if you want it to work correctly in Windows. I've edited the answer. – Flimm Aug 12 '16 at 15:06
  • I tried and tried this, but I had to do a case of instance_of_modelName.icon_id = image. Admittedly, my case was an add-on to an existing model, so I couldn't create new. – bethlakshmi Jul 02 '17 at 22:52