2008-08-09 04:59:02 +08:00
|
|
|
import datetime
|
2016-03-21 09:51:17 +08:00
|
|
|
import posixpath
|
2008-08-09 04:59:02 +08:00
|
|
|
|
2011-07-13 17:35:51 +08:00
|
|
|
from django import forms
|
2014-01-20 10:45:21 +08:00
|
|
|
from django.core import checks
|
2011-07-13 17:35:51 +08:00
|
|
|
from django.core.files.base import File
|
|
|
|
from django.core.files.images import ImageFile
|
2020-03-31 18:12:39 +08:00
|
|
|
from django.core.files.storage import Storage, default_storage
|
2021-04-15 00:23:44 +08:00
|
|
|
from django.core.files.utils import validate_file_name
|
2008-08-09 04:59:02 +08:00
|
|
|
from django.db.models import signals
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.db.models.fields import Field
|
2020-06-12 20:58:53 +08:00
|
|
|
from django.db.models.query_utils import DeferredAttribute
|
2017-01-27 03:58:33 +08:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2008-08-09 04:59:02 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
class FieldFile(File):
|
|
|
|
def __init__(self, instance, field, name):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(None, name)
|
2008-08-09 04:59:02 +08:00
|
|
|
self.instance = instance
|
|
|
|
self.field = field
|
|
|
|
self.storage = field.storage
|
2009-01-17 05:48:37 +08:00
|
|
|
self._committed = True
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
# Older code may be expecting FileField values to be simple strings.
|
|
|
|
# By overriding the == operator, it can remain backwards compatibility.
|
|
|
|
if hasattr(other, "name"):
|
|
|
|
return self.name == other.name
|
|
|
|
return self.name == other
|
|
|
|
|
2009-03-08 17:59:17 +08:00
|
|
|
def __hash__(self):
|
|
|
|
return hash(self.name)
|
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
# The standard File contains most of the necessary properties, but
|
|
|
|
# FieldFiles can be instantiated without a name, so that needs to
|
|
|
|
# be checked for here.
|
|
|
|
|
|
|
|
def _require_file(self):
|
|
|
|
if not self:
|
|
|
|
raise ValueError(
|
|
|
|
"The '%s' attribute has no file associated with it." % self.field.name
|
|
|
|
)
|
|
|
|
|
2016-06-18 09:04:02 +08:00
|
|
|
def _get_file(self):
|
2008-08-09 04:59:02 +08:00
|
|
|
self._require_file()
|
2018-01-04 02:24:02 +08:00
|
|
|
if getattr(self, "_file", None) is None:
|
2016-06-18 09:04:02 +08:00
|
|
|
self._file = self.storage.open(self.name, "rb")
|
2008-08-09 04:59:02 +08:00
|
|
|
return self._file
|
2009-05-08 23:08:09 +08:00
|
|
|
|
|
|
|
def _set_file(self, file):
|
|
|
|
self._file = file
|
|
|
|
|
|
|
|
def _del_file(self):
|
|
|
|
del self._file
|
|
|
|
|
|
|
|
file = property(_get_file, _set_file, _del_file)
|
2008-08-09 04:59:02 +08:00
|
|
|
|
2016-08-26 08:06:22 +08:00
|
|
|
@property
|
|
|
|
def path(self):
|
2008-08-09 04:59:02 +08:00
|
|
|
self._require_file()
|
|
|
|
return self.storage.path(self.name)
|
|
|
|
|
2016-08-26 08:06:22 +08:00
|
|
|
@property
|
|
|
|
def url(self):
|
2008-08-09 04:59:02 +08:00
|
|
|
self._require_file()
|
|
|
|
return self.storage.url(self.name)
|
|
|
|
|
2016-08-26 08:06:22 +08:00
|
|
|
@property
|
|
|
|
def size(self):
|
2008-08-28 05:30:47 +08:00
|
|
|
self._require_file()
|
2009-05-08 23:08:09 +08:00
|
|
|
if not self._committed:
|
2010-12-13 06:54:22 +08:00
|
|
|
return self.file.size
|
2008-08-28 05:30:47 +08:00
|
|
|
return self.storage.size(self.name)
|
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
def open(self, mode="rb"):
|
2016-06-18 09:04:02 +08:00
|
|
|
self._require_file()
|
2018-01-04 00:34:10 +08:00
|
|
|
if getattr(self, "_file", None) is None:
|
2016-07-20 04:17:39 +08:00
|
|
|
self.file = self.storage.open(self.name, mode)
|
2018-01-04 00:34:10 +08:00
|
|
|
else:
|
|
|
|
self.file.open(mode)
|
2017-04-07 20:21:06 +08:00
|
|
|
return self
|
2022-02-04 03:24:19 +08:00
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
# open() doesn't alter the file's contents, but it does reset the pointer
|
|
|
|
open.alters_data = True
|
|
|
|
|
|
|
|
# In addition to the standard File API, FieldFiles have extra methods
|
|
|
|
# to further manipulate the underlying file, as well as update the
|
|
|
|
# associated model instance.
|
|
|
|
|
|
|
|
def save(self, name, content, save=True):
|
|
|
|
name = self.field.generate_filename(self.instance, name)
|
2015-08-20 21:43:07 +08:00
|
|
|
self.name = self.storage.save(name, content, max_length=self.field.max_length)
|
2020-10-12 13:22:59 +08:00
|
|
|
setattr(self.instance, self.field.attname, self.name)
|
2009-01-17 05:48:37 +08:00
|
|
|
self._committed = True
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
# Save the object because it has changed, unless save is False
|
|
|
|
if save:
|
|
|
|
self.instance.save()
|
2022-02-04 03:24:19 +08:00
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
save.alters_data = True
|
|
|
|
|
|
|
|
def delete(self, save=True):
|
2013-06-27 16:58:05 +08:00
|
|
|
if not self:
|
|
|
|
return
|
2008-08-28 05:18:45 +08:00
|
|
|
# Only close the file if it's already open, which we know by the
|
|
|
|
# presence of self._file
|
|
|
|
if hasattr(self, "_file"):
|
|
|
|
self.close()
|
2009-05-08 23:08:09 +08:00
|
|
|
del self.file
|
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
self.storage.delete(self.name)
|
|
|
|
|
2009-05-08 23:08:09 +08:00
|
|
|
self.name = None
|
2020-10-12 13:22:59 +08:00
|
|
|
setattr(self.instance, self.field.attname, self.name)
|
2009-01-17 05:48:37 +08:00
|
|
|
self._committed = False
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
if save:
|
|
|
|
self.instance.save()
|
2022-02-04 03:24:19 +08:00
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
delete.alters_data = True
|
|
|
|
|
2016-08-26 08:06:22 +08:00
|
|
|
@property
|
|
|
|
def closed(self):
|
2009-05-11 17:57:19 +08:00
|
|
|
file = getattr(self, "_file", None)
|
|
|
|
return file is None or file.closed
|
|
|
|
|
2009-05-08 23:08:09 +08:00
|
|
|
def close(self):
|
|
|
|
file = getattr(self, "_file", None)
|
|
|
|
if file is not None:
|
|
|
|
file.close()
|
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
def __getstate__(self):
|
2019-11-11 05:55:48 +08:00
|
|
|
# FieldFile needs access to its associated model field, an instance and
|
|
|
|
# the file's name. Everything else will be restored later, by
|
|
|
|
# FileDescriptor below.
|
|
|
|
return {
|
|
|
|
"name": self.name,
|
|
|
|
"closed": False,
|
|
|
|
"_committed": True,
|
|
|
|
"_file": None,
|
|
|
|
"instance": self.instance,
|
|
|
|
"field": self.field,
|
|
|
|
}
|
|
|
|
|
|
|
|
def __setstate__(self, state):
|
|
|
|
self.__dict__.update(state)
|
|
|
|
self.storage = self.field.storage
|
2008-08-09 04:59:02 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2020-06-12 20:58:53 +08:00
|
|
|
class FileDescriptor(DeferredAttribute):
|
2009-05-11 17:57:19 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
The descriptor for the file attribute on the model instance. Return a
|
|
|
|
FieldFile when accessed so you can write code like::
|
2009-05-28 13:46:09 +08:00
|
|
|
|
2013-10-11 19:25:14 +08:00
|
|
|
>>> from myapp.models import MyModel
|
|
|
|
>>> instance = MyModel.objects.get(pk=1)
|
2009-05-11 17:57:19 +08:00
|
|
|
>>> instance.file.size
|
2009-05-28 13:46:09 +08:00
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
Assign a file object on assignment so you can do::
|
2009-05-28 13:46:09 +08:00
|
|
|
|
2019-01-28 00:30:20 +08:00
|
|
|
>>> with open('/path/to/hello.world') as f:
|
2013-10-11 19:25:14 +08:00
|
|
|
... instance.file = File(f)
|
2009-05-11 17:57:19 +08:00
|
|
|
"""
|
2022-02-04 03:24:19 +08:00
|
|
|
|
2015-10-26 23:31:16 +08:00
|
|
|
def __get__(self, instance, cls=None):
|
2008-08-09 04:59:02 +08:00
|
|
|
if instance is None:
|
2015-10-02 01:00:44 +08:00
|
|
|
return self
|
2009-05-28 13:46:09 +08:00
|
|
|
|
2009-05-11 17:57:19 +08:00
|
|
|
# This is slightly complicated, so worth an explanation.
|
|
|
|
# instance.file`needs to ultimately return some instance of `File`,
|
|
|
|
# probably a subclass. Additionally, this returned object needs to have
|
|
|
|
# the FieldFile API so that users can easily do things like
|
|
|
|
# instance.file.path and have that delegated to the file storage engine.
|
|
|
|
# Easy enough if we're strict about assignment in __set__, but if you
|
|
|
|
# peek below you can see that we're not. So depending on the current
|
|
|
|
# value of the field we have to dynamically construct some sort of
|
|
|
|
# "thing" to return.
|
2009-05-28 13:46:09 +08:00
|
|
|
|
|
|
|
# The instance dict contains whatever was originally assigned
|
2009-05-11 17:57:19 +08:00
|
|
|
# in __set__.
|
2020-06-12 20:58:53 +08:00
|
|
|
file = super().__get__(instance, cls)
|
2009-05-11 17:57:19 +08:00
|
|
|
|
|
|
|
# If this value is a string (instance.file = "path/to/file") or None
|
|
|
|
# then we simply wrap it with the appropriate attribute class according
|
|
|
|
# to the file field. [This is FieldFile for FileFields and
|
|
|
|
# ImageFieldFile for ImageFields; it's also conceivable that user
|
|
|
|
# subclasses might also want to subclass the attribute class]. This
|
|
|
|
# object understands how to convert a path to a file, and also how to
|
|
|
|
# handle None.
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(file, str) or file is None:
|
2009-05-11 17:57:19 +08:00
|
|
|
attr = self.field.attr_class(instance, self.field, file)
|
2020-06-12 20:58:53 +08:00
|
|
|
instance.__dict__[self.field.attname] = attr
|
2009-05-11 17:57:19 +08:00
|
|
|
|
|
|
|
# Other types of files may be assigned as well, but they need to have
|
2015-02-21 06:47:41 +08:00
|
|
|
# the FieldFile interface added to them. Thus, we wrap any other type of
|
2009-05-28 13:46:09 +08:00
|
|
|
# File inside a FieldFile (well, the field's attr_class, which is
|
2009-05-11 17:57:19 +08:00
|
|
|
# usually FieldFile).
|
2009-01-17 05:48:37 +08:00
|
|
|
elif isinstance(file, File) and not isinstance(file, FieldFile):
|
2009-05-08 23:08:09 +08:00
|
|
|
file_copy = self.field.attr_class(instance, self.field, file.name)
|
|
|
|
file_copy.file = file
|
2009-01-17 05:48:37 +08:00
|
|
|
file_copy._committed = False
|
2020-06-12 20:58:53 +08:00
|
|
|
instance.__dict__[self.field.attname] = file_copy
|
2009-05-28 13:46:09 +08:00
|
|
|
|
2009-05-11 17:57:19 +08:00
|
|
|
# Finally, because of the (some would say boneheaded) way pickle works,
|
|
|
|
# the underlying FieldFile might not actually itself have an associated
|
|
|
|
# file. So we need to reset the details of the FieldFile in those cases.
|
2009-01-17 05:48:37 +08:00
|
|
|
elif isinstance(file, FieldFile) and not hasattr(file, "field"):
|
2008-08-09 04:59:02 +08:00
|
|
|
file.instance = instance
|
|
|
|
file.field = self.field
|
|
|
|
file.storage = self.field.storage
|
2009-05-28 13:46:09 +08:00
|
|
|
|
2015-12-05 09:14:46 +08:00
|
|
|
# Make sure that the instance is correct.
|
|
|
|
elif isinstance(file, FieldFile) and instance is not file.instance:
|
|
|
|
file.instance = instance
|
|
|
|
|
2009-05-11 17:57:19 +08:00
|
|
|
# That was fun, wasn't it?
|
2020-06-12 20:58:53 +08:00
|
|
|
return instance.__dict__[self.field.attname]
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
def __set__(self, instance, value):
|
2020-06-12 20:58:53 +08:00
|
|
|
instance.__dict__[self.field.attname] = value
|
2008-08-09 04:59:02 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
class FileField(Field):
|
2012-05-17 22:02:05 +08:00
|
|
|
|
2009-05-11 17:57:19 +08:00
|
|
|
# The class to wrap instance attributes in. Accessing the file object off
|
|
|
|
# the instance will always return an instance of attr_class.
|
2008-08-09 04:59:02 +08:00
|
|
|
attr_class = FieldFile
|
2009-05-28 13:46:09 +08:00
|
|
|
|
2009-05-11 17:57:19 +08:00
|
|
|
# The descriptor to use for accessing the attribute off of the class.
|
|
|
|
descriptor_class = FileDescriptor
|
2008-08-09 04:59:02 +08:00
|
|
|
|
2012-02-10 02:57:54 +08:00
|
|
|
description = _("File")
|
2009-12-17 02:13:34 +08:00
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
def __init__(
|
|
|
|
self, verbose_name=None, name=None, upload_to="", storage=None, **kwargs
|
|
|
|
):
|
2014-01-20 10:45:21 +08:00
|
|
|
self._primary_key_set_explicitly = "primary_key" in kwargs
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
self.storage = storage or default_storage
|
2020-03-31 18:12:39 +08:00
|
|
|
if callable(self.storage):
|
2020-08-25 03:27:22 +08:00
|
|
|
# Hold a reference to the callable for deconstruct().
|
|
|
|
self._storage_callable = self.storage
|
2020-03-31 18:12:39 +08:00
|
|
|
self.storage = self.storage()
|
|
|
|
if not isinstance(self.storage, Storage):
|
|
|
|
raise TypeError(
|
|
|
|
"%s.storage must be a subclass/instance of %s.%s"
|
|
|
|
% (
|
|
|
|
self.__class__.__qualname__,
|
|
|
|
Storage.__module__,
|
|
|
|
Storage.__qualname__,
|
|
|
|
)
|
|
|
|
)
|
2008-08-09 04:59:02 +08:00
|
|
|
self.upload_to = upload_to
|
|
|
|
|
2017-12-04 23:52:27 +08:00
|
|
|
kwargs.setdefault("max_length", 100)
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(verbose_name, name, **kwargs)
|
2008-08-09 04:59:02 +08:00
|
|
|
|
2014-01-20 10:45:21 +08:00
|
|
|
def check(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return [
|
|
|
|
*super().check(**kwargs),
|
|
|
|
*self._check_primary_key(),
|
|
|
|
*self._check_upload_to(),
|
|
|
|
]
|
2014-01-20 10:45:21 +08:00
|
|
|
|
|
|
|
def _check_primary_key(self):
|
|
|
|
if self._primary_key_set_explicitly:
|
|
|
|
return [
|
|
|
|
checks.Error(
|
2014-03-03 18:18:39 +08:00
|
|
|
"'primary_key' is not a valid argument for a %s."
|
|
|
|
% self.__class__.__name__,
|
2014-01-20 10:45:21 +08:00
|
|
|
obj=self,
|
2014-03-03 18:18:39 +08:00
|
|
|
id="fields.E201",
|
2014-01-20 10:45:21 +08:00
|
|
|
)
|
|
|
|
]
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
2016-11-27 02:23:03 +08:00
|
|
|
def _check_upload_to(self):
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(self.upload_to, str) and self.upload_to.startswith("/"):
|
2016-11-27 02:23:03 +08:00
|
|
|
return [
|
|
|
|
checks.Error(
|
|
|
|
"%s's 'upload_to' argument must be a relative path, not an "
|
|
|
|
"absolute path." % self.__class__.__name__,
|
|
|
|
obj=self,
|
|
|
|
id="fields.E202",
|
|
|
|
hint="Remove the leading slash.",
|
|
|
|
)
|
|
|
|
]
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
2013-06-29 00:26:05 +08:00
|
|
|
def deconstruct(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2015-05-14 02:51:18 +08:00
|
|
|
if kwargs.get("max_length") == 100:
|
2013-06-29 00:26:05 +08:00
|
|
|
del kwargs["max_length"]
|
|
|
|
kwargs["upload_to"] = self.upload_to
|
|
|
|
if self.storage is not default_storage:
|
2020-08-25 03:27:22 +08:00
|
|
|
kwargs["storage"] = getattr(self, "_storage_callable", self.storage)
|
2013-06-29 00:26:05 +08:00
|
|
|
return name, path, args, kwargs
|
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "FileField"
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().get_prep_value(value)
|
2017-01-20 17:20:53 +08:00
|
|
|
# Need to convert File objects provided via a form to string for
|
|
|
|
# database insertion.
|
2008-08-09 04:59:02 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
2016-12-29 23:27:49 +08:00
|
|
|
return str(value)
|
2008-08-09 04:59:02 +08:00
|
|
|
|
2009-01-17 05:48:37 +08:00
|
|
|
def pre_save(self, model_instance, add):
|
2017-01-21 21:13:44 +08:00
|
|
|
file = super().pre_save(model_instance, add)
|
2009-01-17 05:48:37 +08:00
|
|
|
if file and not file._committed:
|
|
|
|
# Commit the file to storage prior to saving the model
|
2016-10-14 11:13:43 +08:00
|
|
|
file.save(file.name, file.file, save=False)
|
2009-01-17 05:48:37 +08:00
|
|
|
return file
|
|
|
|
|
2020-07-23 07:38:31 +08:00
|
|
|
def contribute_to_class(self, cls, name, **kwargs):
|
|
|
|
super().contribute_to_class(cls, name, **kwargs)
|
|
|
|
setattr(cls, self.attname, self.descriptor_class(self))
|
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
def generate_filename(self, instance, filename):
|
2016-03-21 09:51:17 +08:00
|
|
|
"""
|
|
|
|
Apply (if callable) or prepend (if a string) upload_to to the filename,
|
|
|
|
then delegate further processing of the name to the storage backend.
|
|
|
|
Until the storage layer, all file paths are expected to be Unix style
|
|
|
|
(with forward slashes).
|
|
|
|
"""
|
2015-05-03 12:10:24 +08:00
|
|
|
if callable(self.upload_to):
|
2016-03-21 09:51:17 +08:00
|
|
|
filename = self.upload_to(instance, filename)
|
|
|
|
else:
|
2019-08-18 17:40:11 +08:00
|
|
|
dirname = datetime.datetime.now().strftime(str(self.upload_to))
|
2016-03-21 09:51:17 +08:00
|
|
|
filename = posixpath.join(dirname, filename)
|
2021-05-13 14:53:44 +08:00
|
|
|
filename = validate_file_name(filename, allow_relative_path=True)
|
2016-03-21 09:51:17 +08:00
|
|
|
return self.storage.generate_filename(filename)
|
2008-08-09 04:59:02 +08:00
|
|
|
|
2009-02-17 01:30:12 +08:00
|
|
|
def save_form_data(self, instance, data):
|
2010-10-01 10:02:58 +08:00
|
|
|
# Important: None means "no change", other false value means "clear"
|
|
|
|
# This subtle distinction (rather than a more explicit marker) is
|
|
|
|
# needed because we need to consume values that are also sane for a
|
|
|
|
# regular (non Model-) Form to find in its cleaned_data dictionary.
|
|
|
|
if data is not None:
|
2017-01-21 05:04:05 +08:00
|
|
|
# This value will be converted to str and stored in the
|
2010-10-01 10:02:58 +08:00
|
|
|
# database, so leaving False as-is is not acceptable.
|
2018-01-04 07:52:12 +08:00
|
|
|
setattr(instance, self.name, data or "")
|
2009-02-17 01:30:12 +08:00
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
def formfield(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
|
|
|
"form_class": forms.FileField,
|
|
|
|
"max_length": self.max_length,
|
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2008-08-09 04:59:02 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2009-05-11 17:57:19 +08:00
|
|
|
class ImageFileDescriptor(FileDescriptor):
|
|
|
|
"""
|
|
|
|
Just like the FileDescriptor, but for ImageFields. The only difference is
|
|
|
|
assigning the width/height to the width_field/height_field, if appropriate.
|
|
|
|
"""
|
2022-02-04 03:24:19 +08:00
|
|
|
|
2009-05-11 17:57:19 +08:00
|
|
|
def __set__(self, instance, value):
|
2020-06-12 20:58:53 +08:00
|
|
|
previous_file = instance.__dict__.get(self.field.attname)
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__set__(instance, value)
|
2009-05-28 13:46:09 +08:00
|
|
|
|
|
|
|
# To prevent recalculating image dimensions when we are instantiating
|
|
|
|
# an object from the database (bug #11084), only update dimensions if
|
|
|
|
# the field had a value before this assignment. Since the default
|
|
|
|
# value for FileField subclasses is an instance of field.attr_class,
|
|
|
|
# previous_file will only be None when we are called from
|
|
|
|
# Model.__init__(). The ImageField.update_dimension_fields method
|
|
|
|
# hooked up to the post_init signal handles the Model.__init__() cases.
|
|
|
|
# Assignment happening outside of Model.__init__() will trigger the
|
|
|
|
# update right here.
|
|
|
|
if previous_file is not None:
|
|
|
|
self.field.update_dimension_fields(instance, force=True)
|
2008-08-09 04:59:02 +08:00
|
|
|
|
2011-07-13 17:35:51 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
class ImageFieldFile(ImageFile, FieldFile):
|
2008-08-09 04:59:02 +08:00
|
|
|
def delete(self, save=True):
|
|
|
|
# Clear the image dimensions cache
|
|
|
|
if hasattr(self, "_dimensions_cache"):
|
|
|
|
del self._dimensions_cache
|
2017-01-21 21:13:44 +08:00
|
|
|
super().delete(save)
|
2008-08-09 04:59:02 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
class ImageField(FileField):
|
|
|
|
attr_class = ImageFieldFile
|
2009-05-11 17:57:19 +08:00
|
|
|
descriptor_class = ImageFileDescriptor
|
2012-02-10 02:57:54 +08:00
|
|
|
description = _("Image")
|
2008-08-09 04:59:02 +08:00
|
|
|
|
2016-03-29 06:33:29 +08:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
verbose_name=None,
|
|
|
|
name=None,
|
|
|
|
width_field=None,
|
|
|
|
height_field=None,
|
|
|
|
**kwargs,
|
|
|
|
):
|
2008-08-09 04:59:02 +08:00
|
|
|
self.width_field, self.height_field = width_field, height_field
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(verbose_name, name, **kwargs)
|
2008-08-09 04:59:02 +08:00
|
|
|
|
2014-01-20 10:45:21 +08:00
|
|
|
def check(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return [
|
|
|
|
*super().check(**kwargs),
|
|
|
|
*self._check_image_library_installed(),
|
|
|
|
]
|
2014-01-20 10:45:21 +08:00
|
|
|
|
|
|
|
def _check_image_library_installed(self):
|
|
|
|
try:
|
2014-03-21 22:54:53 +08:00
|
|
|
from PIL import Image # NOQA
|
|
|
|
except ImportError:
|
2014-01-20 10:45:21 +08:00
|
|
|
return [
|
|
|
|
checks.Error(
|
2014-03-03 18:18:39 +08:00
|
|
|
"Cannot use ImageField because Pillow is not installed.",
|
2018-04-18 06:19:29 +08:00
|
|
|
hint=(
|
|
|
|
"Get Pillow at https://pypi.org/project/Pillow/ "
|
2019-04-14 23:02:36 +08:00
|
|
|
'or run command "python -m pip install Pillow".'
|
|
|
|
),
|
2014-01-20 10:45:21 +08:00
|
|
|
obj=self,
|
2014-03-03 18:18:39 +08:00
|
|
|
id="fields.E210",
|
2014-01-20 10:45:21 +08:00
|
|
|
)
|
|
|
|
]
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
2013-06-29 00:26:05 +08:00
|
|
|
def deconstruct(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2013-06-29 00:26:05 +08:00
|
|
|
if self.width_field:
|
|
|
|
kwargs["width_field"] = self.width_field
|
|
|
|
if self.height_field:
|
|
|
|
kwargs["height_field"] = self.height_field
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
2014-07-23 17:41:06 +08:00
|
|
|
def contribute_to_class(self, cls, name, **kwargs):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().contribute_to_class(cls, name, **kwargs)
|
2009-05-28 13:46:09 +08:00
|
|
|
# Attach update_dimension_fields so that dimension fields declared
|
|
|
|
# after their corresponding image field don't stay cleared by
|
|
|
|
# Model.__init__, see bug #11196.
|
2013-10-04 01:44:10 +08:00
|
|
|
# Only run post-initialization dimension update on non-abstract models
|
|
|
|
if not cls._meta.abstract:
|
|
|
|
signals.post_init.connect(self.update_dimension_fields, sender=cls)
|
2009-05-28 13:46:09 +08:00
|
|
|
|
|
|
|
def update_dimension_fields(self, instance, force=False, *args, **kwargs):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Update field's width and height fields, if defined.
|
2009-05-28 13:46:09 +08:00
|
|
|
|
|
|
|
This method is hooked up to model's post_init signal to update
|
|
|
|
dimensions after instantiating a model instance. However, dimensions
|
|
|
|
won't be updated if the dimensions fields are already populated. This
|
|
|
|
avoids unnecessary recalculation when loading an object from the
|
|
|
|
database.
|
|
|
|
|
|
|
|
Dimensions can be forced to update with force=True, which is how
|
|
|
|
ImageFileDescriptor.__set__ calls this method.
|
|
|
|
"""
|
2016-07-16 03:54:11 +08:00
|
|
|
# Nothing to update if the field doesn't have dimension fields or if
|
|
|
|
# the field is deferred.
|
2009-05-28 13:46:09 +08:00
|
|
|
has_dimension_fields = self.width_field or self.height_field
|
2016-07-16 03:54:11 +08:00
|
|
|
if not has_dimension_fields or self.attname not in instance.__dict__:
|
2009-05-28 13:46:09 +08:00
|
|
|
return
|
|
|
|
|
|
|
|
# getattr will call the ImageFileDescriptor's __get__ method, which
|
|
|
|
# coerces the assigned value into an instance of self.attr_class
|
|
|
|
# (ImageFieldFile in this case).
|
|
|
|
file = getattr(instance, self.attname)
|
|
|
|
|
|
|
|
# Nothing to update if we have no file and not being forced to update.
|
|
|
|
if not file and not force:
|
|
|
|
return
|
|
|
|
|
|
|
|
dimension_fields_filled = not (
|
2016-04-04 08:37:32 +08:00
|
|
|
(self.width_field and not getattr(instance, self.width_field))
|
|
|
|
or (self.height_field and not getattr(instance, self.height_field))
|
2009-05-28 13:46:09 +08:00
|
|
|
)
|
|
|
|
# When both dimension fields have values, we are most likely loading
|
|
|
|
# data from the database or updating an image field that already had
|
|
|
|
# an image stored. In the first case, we don't want to update the
|
|
|
|
# dimension fields because we are already getting their values from the
|
|
|
|
# database. In the second case, we do want to update the dimensions
|
|
|
|
# fields and will skip this return because force will be True since we
|
|
|
|
# were called from ImageFileDescriptor.__set__.
|
|
|
|
if dimension_fields_filled and not force:
|
|
|
|
return
|
|
|
|
|
|
|
|
# file should be an instance of ImageFieldFile or should be None.
|
|
|
|
if file:
|
|
|
|
width = file.width
|
|
|
|
height = file.height
|
|
|
|
else:
|
|
|
|
# No file, so clear dimensions fields.
|
|
|
|
width = None
|
|
|
|
height = None
|
|
|
|
|
|
|
|
# Update the width and height fields.
|
|
|
|
if self.width_field:
|
|
|
|
setattr(instance, self.width_field, width)
|
|
|
|
if self.height_field:
|
|
|
|
setattr(instance, self.height_field, height)
|
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
def formfield(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
|
|
|
"form_class": forms.ImageField,
|
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|