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

本小妞迷上赌 提交于 2020-01-01 10:03:24

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/20635332/how-to-programmatically-fill-or-create-filer-fields-image-filerimagefield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!