[Answer]-What is wrong with my custom model field?

1👍

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)

    """

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

return None or file

UPDATE:

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

Leave a comment