我尝试实现一个可以为其分配字符串的图像字段,它会自动从该 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__
模型的 中。谁可以给我解释一下这个?我怎样才能找到解决方法?