0

我尝试实现一个可以为其分配字符串的图像字段,它会自动从该 URL 获取图像。之后读取它,它将保存到本地副本的路径。因此,我继承自 DjangoImageField及其描述符类。

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__模型的 中。谁可以给我解释一下这个?我怎样才能找到解决方法?

4

1 回答 1

1

问题是您需要返回 a 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)

    """

所以你需要返回一个FieldFileString只是做它改变这个回报。

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!!
于 2014-07-26T19:11:22.127 回答