Subclassing the Django ImageFileField

萝らか妹 提交于 2019-12-04 14:48:09

问题


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?


回答1:


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?




回答2:


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



来源:https://stackoverflow.com/questions/3973586/subclassing-the-django-imagefilefield

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