Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically fill or create filer.fields.image.FilerImageField?

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?

like image 1000
Sergey Avatar asked Dec 17 '13 13:12

Sergey


1 Answers

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.

like image 85
iMom0 Avatar answered Sep 30 '22 14:09

iMom0