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

时间:2014-07-26 09:58:59

标签: python django django-1.7

我尝试实现一个可以分配字符串的图像字段,它会自动从该URL获取图像。之后读它,它将保存本地副本的路径。因此,我继承了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 个答案:

答案 0 :(得分: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!!