子类化 Django ImageFileField

发布于 2024-09-28 08:58:56 字数 718 浏览 3 评论 0原文

我对 django 的 ImageFileField 子类化以允许访问图像 IPTC 元数据感兴趣,例如:

>>> from myapp.models import SomeModel
>>> obj = SomeModel.objects.all()[0] # or what have you
>>> obj.image.iptc['keywords']
('keyword','anotherkeyword','etc')

... 文档对 阅读 django 的内部代码,我就是这么做的;我试图生成一个有效的实现,但我不确定我在做什么——我之前定义了自定义字段,但我无法为基于文件的字段提供样板设置。

我知道我需要定义一个 attr_class 和一个 descriptor_class 才能使其工作。有没有人有一个简单的例子或建议,我可以从中开始?

I'm interested in subclassing django's ImageFileField to allow access to the image IPTC metadata, something like:

>>> from myapp.models import SomeModel
>>> obj = SomeModel.objects.all()[0] # or what have you
>>> obj.image.iptc['keywords']
('keyword','anotherkeyword','etc')

... the docs say to read over django's internal code, which I did; I've tried to produce a working implementation and I am not sure what I'm doing -- I've defined custom fields before, but I can't come up with boilerplate setup for a file-based field.

I know I need to define an attr_class and a descriptor_class to make it work. Does anyone have a straightforward example or suggestion, with which I could get started?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

轻拂→两袖风尘 2024-10-05 08:58:56

你的问题并不清楚:你尝试过这样的事情吗?

class ImageMetadataMixin(object):
    """Mixin can be added to any image file"""
    @property
    def iptc(self):
        """Or something like this"""

class ImageWithMetadataFieldFile(ImageMetadataMixin, ImageFieldFile):
    pass

class ImageWithMetadataField(ImageField):
    attr_class = ImageWithMetadataFieldFile

我认为这都是必要的。您认为为什么需要重新定义descriptor_class

It's not clear from your question: have you tried something like this?

class ImageMetadataMixin(object):
    """Mixin can be added to any image file"""
    @property
    def iptc(self):
        """Or something like this"""

class ImageWithMetadataFieldFile(ImageMetadataMixin, ImageFieldFile):
    pass

class ImageWithMetadataField(ImageField):
    attr_class = ImageWithMetadataFieldFile

I think it's all what necessary. Why do you think you need to redefine descriptor_class?

你是我的挚爱i 2024-10-05 08:58:56

更新:我已经弄清楚了这一点——部分感谢@valya 提供的答案。成功实现的示例可以在我的 django-imagekit 分支中找到:

https://github.com/fish2000/django-imagekit/blob/icc-develop/imagekit/modelfields.py

UPDATE: I have figured this one out -- thanks in part to the answer @valya provided. An example of a successful implementation can be found in my fork of django-imagekit:

https://github.com/fish2000/django-imagekit/blob/icc-develop/imagekit/modelfields.py

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文