我的自定义模型字段有什么问题? [英] What is wrong with my custom model field?

查看:54
本文介绍了我的自定义模型字段有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to implement an image field that you can assign a string to and it will automatically fetch the image from that URL. Reading it afterwards, it will hold the path to the local copy. Therefore, I inherited from Django's ImageField and its descriptor class.

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'对象没有属性'_committed'.这是Django 1.7c1中的相关代码.它位于db/models/fields/files.py中.该异常发生在if语句的行上.

When saving the model that uses this field, Django code raises an error 'str' object has no attribute '_committed'. This is the related code from Django 1.7c1. It lives in db/models/fields/files.py. The exception occurs on the line of the if statement.

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 __ 返回字符串.但是,它使用 ContentFile 调用其基类的 __ get __ ,因此应将其存储在模型的 __ dict __ 中.谁可以给我解释一下这个?如何找到解决方法?

I don't understand file being a string here. The only thing I can think of is that the descriptor classes __get__ returns string. However, it calls the __get__ of its base class with a ContentFile, so that should be stored in the __dict__ of the model. Can someone explain this to me? How can I find a workaround?

推荐答案

问题是您需要返回一个 FieldFile ,以便您可以在Django的源代码中访问它的属性代码,您可以找到名为 FileDescriptor 这是 ImageFileDescriptor的父项,如果您在名称下查看 FileDescriptor 类,则可以找到该类的文档,并显示:

The problem is that you need to return a FieldFile, so that way you can access to the properties of it, in django's source code you can find a class named FileDescriptor this is the parent of ImageFileDescriptor, if you look at the FileDescriptor class under the name you can find the doc of the class and it says:

 """
    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 ,只需更改它的返回值即可.

So you need to return a FieldFile not a String just do it changing the return for this.

return None or file

更新:

我发现了您的问题,此代码对我有用:

I figured out your problem and this code works for me:

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!!

这篇关于我的自定义模型字段有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆