forked from jazzband/sorl-thumbnail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfields.py
72 lines (61 loc) · 2.65 KB
/
fields.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from __future__ import with_statement
from django.db import models
from django.db.models import Q
from django import forms
from django.utils.translation import ugettext_lazy as _
from sorl.thumbnail import default
__all__ = ('ImageField', 'ImageFormField')
class ImageField(models.FileField):
def delete_file(self, instance, sender, **kwargs):
"""
Adds deletion of thumbnails and key kalue store references to the
parent class implementation. Only called in Django < 1.2.5
"""
file_ = getattr(instance, self.attname)
# If no other object of this type references the file, and it's not the
# default value for future objects, delete it from the backend.
query = Q(**{self.name: file_.name}) & ~Q(pk=instance.pk)
qs = sender._default_manager.filter(query)
if (file_ and file_.name != self.default and not qs):
default.backend.delete(file_)
elif file_:
# Otherwise, just close the file, so it doesn't tie up resources.
file_.close()
def formfield(self, **kwargs):
defaults = {'form_class': ImageFormField}
defaults.update(kwargs)
return super(ImageField, self).formfield(**defaults)
def save_form_data(self, instance, data):
if data is not None:
setattr(instance, self.name, data or '')
def south_field_triple(self):
from south.modelsinspector import introspector
cls_name = '%s.%s' % (self.__class__.__module__ , self.__class__.__name__)
args, kwargs = introspector(self)
return (cls_name, args, kwargs)
class ImageFormField(forms.FileField):
default_error_messages = {
'invalid_image': _(u"Upload a valid image. The file you uploaded was "
u"either not an image or a corrupted image."),
}
def to_python(self, data):
"""
Checks that the file-upload field data contains a valid image (GIF,
JPG, PNG, possibly others -- whatever the engine supports).
"""
f = super(ImageFormField, self).to_python(data)
if f is None:
return None
# We need to get a file raw data to validate it.
if hasattr(data, 'temporary_file_path'):
with open(data.temporary_file_path(), 'rb') as fp:
raw_data = fp.read()
elif hasattr(data, 'read'):
raw_data = data.read()
else:
raw_data = data['content']
if not default.engine.is_valid_image(raw_data):
raise forms.ValidationError(self.error_messages['invalid_image'])
if hasattr(f, 'seek') and callable(f.seek):
f.seek(0)
return f