장고에 custom model field을 구현했습니다. 파일을 직접 할당하는 것 외에도 URL 문자열에서 이미지를로드 할 수 있도록 허용하는 이미지 필드입니다.왜 len()이 내 클래스의 __set__을 실행합니까?
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
class UrlImageFileDescriptor(ImageFileDescriptor):
def __set__(self, instance, value):
# If a string is used for assignment, it is used as URL
# to fetch an image from and store it on the server.
if isinstance(value, str):
try:
response = urllib.request.urlopen(value)
image = response.read()
name = str(uuid.uuid4()) + '.png'
value = ContentFile(image, name)
except:
print('Error fetching', value)
pass
super().__set__(instance, value)
class UrlImageField(models.ImageField):
descriptor_class = UrlImageFileDescriptor
일반적으로 필드가 작동합니다. 그러나 어떤 이유로 Django 자체는 문자열 값을 내부적으로 할당합니다. 필드를 사용하는 모델의 쿼리 집합이 필터링 될 때마다 __set__
이 문자열과 함께 호출되므로 except 절의 print 문은 Error fetching upload/to/50e170bf-61b6-4670-90d1-0369a8f9bdb4.png
을 발생시킵니다.
Django 1.7c1에서 django/db/models/query.py
으로 전화를 협상 할 수 있습니다.
왜 내 필드의 __set__
이 실행되는 줄이 있습니까? 입력 값을 유효 URL로 확인하여이 문제를 해결할 수는 있지만 그 이유를 먼저 알고 싶습니다.
오류가 발생한 지점 (즉, except 절 내)에서 전체 추적을 표시 할 수 있습니까? – BrenBarn
@BrenBarn 다음은 [전체 추적에 대한 링크]입니다 (http://pastebin.com/D27CA2QP). – danijar