本文介绍了如何以编程方式填写或创建filer.fields.image.FilerImageField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型类,一个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?

推荐答案

你可以这样做:

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()

图像是<$ c的一个实例$ c> filer.models.Image ,将其分配给Model实例的图标属性, FilerImageField 将为您处理。

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

这篇关于如何以编程方式填写或创建filer.fields.image.FilerImageField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 22:24