How to programmatically fill or create filer.field

2019-04-07 19:11发布

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条回答
聊天终结者
2楼-- · 2019-04-07 19:35

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.

查看更多
登录 后发表回答