我的自定义模型字段有什么问题?

0 投票
1 回答
1138 浏览
提问于 2025-04-18 14:51

我想实现一个图片字段,你可以给它一个字符串,然后它会自动从那个网址获取图片。之后读取的时候,它会保存本地副本的路径。所以,我是从Django的ImageField和它的描述符类继承的。

import uuid
import urllib.request

from django.core.files.base import ContentFile
from django.db import models
from django.db.models.fields.files import ImageFileDescriptor, ImageFieldFile


class UrlImageFileDescriptor(ImageFileDescriptor):
    def __init__(self, field):
        super().__init__(field)

    def __get__(self, instance, owner=None):
        # Get path to local copy on the server
        try:
            file = super().__get__(instance)
            print('Get path to local copy', file.url)
            return file.url if file else None
        except:
            return None

    def __set__(self, instance, value):
        # Set external URL to fetch new image from
        print('Set image from URL', value)
        # Validations
        if not value:
            return
        value = value.strip()
        if len(value) < 1:
            return
        if value == self.__get__(instance):
            return
        # Fetch and store image
        try:
            response = urllib.request.urlopen(value)
            file = response.read()
            name = str(uuid.uuid4()) + '.png'
            content = ContentFile(file, name)
            super().__set__(instance, content)
        except:
            pass

class UrlImageField(models.ImageField):
    descriptor_class = UrlImageFileDescriptor

当我保存使用这个字段的模型时,Django的代码报错了,提示'str' object has no attribute '_committed'。这个错误和Django 1.7c1有关,代码在db/models/fields/files.py文件里。错误发生在if语句那一行。

def pre_save(self, model_instance, add):
    "Returns field's value just before saving."
    file = super(FileField, self).pre_save(model_instance, add)
    if file and not file._committed:
        # Commit the file to storage prior to saving the model
        file.save(file.name, file, save=False)
    return file

我不明白为什么file在这里是一个字符串。我能想到的唯一原因是描述符类的__get__返回了一个字符串。不过,它调用了基类的__get__,并传入了一个ContentFile,所以这个内容应该存储在模型的__dict__里。有人能给我解释一下吗?我该如何找到解决办法?

1 个回答

1

问题在于你需要返回一个 FieldFile 对象,这样你才能访问它的属性。在 Django 的源代码中,有一个叫做 FileDescriptor 的类,它是 ImageFileDescriptor 的父类。如果你查看 FileDescriptor 类的名字下方,你会找到这个类的文档,上面写着:

 """
    The descriptor for the file attribute on the model instance. Returns a
    FieldFile when accessed so you can do stuff like::

        >>> from myapp.models import MyModel
        >>> instance = MyModel.objects.get(pk=1)
        >>> instance.file.size

    Assigns a file object on assignment so you can do::

        >>> with open('/tmp/hello.world', 'r') as f:
        ...     instance.file = File(f)

    """

所以你需要返回一个 FieldFile,而不是一个 String,只需把返回值改成这个就可以了。

return None or file

更新

我找到了你的问题,这段代码对我有效:

import uuid
import requests

from django.core.files.base import ContentFile
from django.db import models
from django.db.models.fields.files import ImageFileDescriptor, ImageFieldFile


class UrlImageFileDescriptor(ImageFileDescriptor):
    def __init__(self, field):
        super(UrlImageFileDescriptor, self).__init__(field)

    def __set__(self, instance, value):
        if not value:
            return
        if isinstance(value, str):
            value = value.strip()
            if len(value) < 1:
                return
            if value == self.__get__(instance):
                return
            # Fetch and store image
            try:
                response = requests.get(value, stream=True)
                _file = ""
                for chunk in response.iter_content():
                    _file+=chunk
                headers = response.headers
                if 'content_type' in headers:
                    content_type = "." + headers['content_type'].split('/')[1]
                else:
                    content_type = "." + value.split('.')[-1]
                name = str(uuid.uuid4()) + content_type
                value = ContentFile(_file, name)
            except Exception as e:
                print e
                pass
        super(UrlImageFileDescriptor,self).__set__(instance, value)

class UrlImageField(models.ImageField):
    descriptor_class = UrlImageFileDescriptor

class TryField(models.Model):
    logo = UrlImageField(upload_to="victor")

custom_field = TryField.objects.create(logo="url_iof_image or File Instance") will work!!

撰写回答