Skip to content

Commit

Permalink
Testing VersatileImageField.save_form_data
Browse files Browse the repository at this point in the history
Includes more code clean-up and minor re-factoring
  • Loading branch information
respondcreate committed Jan 8, 2015
1 parent 3183450 commit 1357554
Show file tree
Hide file tree
Showing 8 changed files with 61 additions and 70 deletions.
4 changes: 1 addition & 3 deletions tests/forms.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from django.forms import ModelForm, ImageField
from django.forms import ModelForm

from .models import VersatileImageTestModel

Expand All @@ -7,8 +7,6 @@ class VersatileImageTestModelForm(ModelForm):
"""
A form for testing VersatileImageFields
"""
image = ImageField()
optional_image = ImageField()

class Meta:
model = VersatileImageTestModel
Expand Down
2 changes: 1 addition & 1 deletion tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class VersatileImageTestModel(models.Model):
ppoi_field='ppoi',
)
optional_image = VersatileImageField(
upload_to='optional/',
upload_to='./',
blank=True
)
ppoi = PPOIField()
32 changes: 25 additions & 7 deletions tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def imageEqual(image1, image2):
rms = math.sqrt(
reduce(
operator.add,
map(lambda a, b: (a - b)**2, h1, h2)
map(lambda a, b: (a - b) ** 2, h1, h2)
) / len(h1)
)
return rms == 0.0
Expand Down Expand Up @@ -758,23 +758,41 @@ def test_save_form_data(self):
'rb'
) as fp:
image_data2 = fp.read()
# Testing new uploads
f = VersatileImageTestModelForm(
data={'img_type': 'xxx'},
files={
'image': SimpleUploadedFile('test.png', image_data),
'optional_image': SimpleUploadedFile('test2.png', image_data2)
'image_0': SimpleUploadedFile('test.png', image_data),
'optional_image_0': SimpleUploadedFile(
'test2.png', image_data2
)
}
)
self.assertEqual(f.is_valid(), True)
self.assertEqual(type(f.cleaned_data['image']), SimpleUploadedFile)
self.assertEqual(type(f.cleaned_data['image'][0]), SimpleUploadedFile)
self.assertEqual(
type(f.cleaned_data['optional_image']), SimpleUploadedFile
type(f.cleaned_data['optional_image'][0]), SimpleUploadedFile
)
instance = f.save()
self.assertEqual(instance.image.name, './test.png')
self.assertEqual(instance.optional_image.name, 'optional/test2.png')
instance.image.delete()
self.assertEqual(instance.optional_image.name, './test2.png')
# Testing updating files / PPOI values
# Deleting optional_image file (since it'll be cleared with the
# next form)
instance.optional_image.delete()
f2 = VersatileImageTestModelForm(
data={
'img_type': 'xxx',
'image_0': '',
'image_1': '0.25x0.25',
'optional_image_0-clear': 'on'
},
instance=instance
)
instance = f2.save()
self.assertEqual(instance.image.ppoi, (0.25, 0.25))
self.assertEqual(instance.optional_image.name, '')
instance.image.delete()

@staticmethod
def SizedImage_with_no_filename_key():
Expand Down
2 changes: 1 addition & 1 deletion versatileimagefield/datastructures/filteredimage.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class FilteredImage(ProcessedImage):
filename to identify it. This should be short
and descriptive (i.e. 'grayscale' or 'invert')
Subclasses must implement a process_filter method.
Subclasses must implement a process_image method.
"""
name = None
url = None
Expand Down
57 changes: 23 additions & 34 deletions versatileimagefield/fields.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db.models import SubfieldBase
from django.db.models.fields import CharField
from django.db.models.fields.files import ImageField
Expand Down Expand Up @@ -88,28 +87,24 @@ def save_form_data(self, instance, data):
"""
to_assign = data
if data is not None:
if data is False:
# OK, it's False, set to an empty string to clear the field
to_assign = ''
if isinstance(data, tuple):
# This value is coming from a MultiValueField
elif isinstance(data, tuple):
if data[0] is None:
# This means the file hasn't changed but we need to
# update the ppoi
current_field = getattr(instance, self.name)
if data[1]:
current_field.ppoi = data[1]
to_assign = current_field
elif data[0] is False:
# This means the 'Clear' checkbox was checked so we
# need to empty the field
to_assign = ''
else:
# This means there is a new upload so we need to unpack
# the tuple and assign the first position to the field
# attribute
to_assign = data[0]
if data[0] is None:
# This means the file hasn't changed but we need to
# update the ppoi
current_field = getattr(instance, self.name)
if data[1]:
current_field.ppoi = data[1]
to_assign = current_field
elif data[0] is False:
# This means the 'Clear' checkbox was checked so we
# need to empty the field
to_assign = ''
else:
# This means there is a new upload so we need to unpack
# the tuple and assign the first position to the field
# attribute
to_assign = data[0]
super(VersatileImageField, self).save_form_data(instance, to_assign)

def formfield(self, **kwargs):
Expand All @@ -126,18 +121,12 @@ class PPOIField(CharField):
def __init__(self, *args, **kwargs):
if 'default' not in kwargs:
kwargs['default'] = '0.5x0.5'
else:
try:
valid_ppoi = validate_ppoi(
kwargs['default'],
return_converted_tuple=True
)
except ValidationError:
raise
else:
kwargs['default'] = self.get_prep_value(
value=valid_ppoi
)
kwargs['default'] = self.get_prep_value(
value=validate_ppoi(
kwargs['default'],
return_converted_tuple=True
)
)
if 'max_length' not in kwargs:
kwargs['max_length'] = 20

Expand Down
7 changes: 2 additions & 5 deletions versatileimagefield/image_warmer.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
from sys import stdout
from django.db.models import Model
try:
from django.db.models import QuerySet
except ImportError:
from django.db.models.query import QuerySet
from django.db.models.query import QuerySet
from .utils import (
get_rendition_key_set,
get_url_from_image_key,
Expand Down Expand Up @@ -141,7 +138,7 @@ def warm(self):
else:
failed_to_create_image_path_list.append(url_or_filepath)

if a*b == total:
if a * b == total:
stdout.write('\n')

stdout.flush()
Expand Down
6 changes: 3 additions & 3 deletions versatileimagefield/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,14 @@

QUAL = SETTINGS.get('jpeg_resize_quality', QUAL)

USE_PLACEHOLDIT = True

VERSATILEIMAGEFIELD_PLACEHOLDER_IMAGE = SETTINGS.get(
'global_placeholder_image',
None
)

if not VERSATILEIMAGEFIELD_PLACEHOLDER_IMAGE:
USE_PLACEHOLDIT = True
else:
if VERSATILEIMAGEFIELD_PLACEHOLDER_IMAGE:
USE_PLACEHOLDIT = False

VERSATILEIMAGEFIELD_CACHE_NAME = SETTINGS.get(
Expand Down
21 changes: 5 additions & 16 deletions versatileimagefield/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,6 @@ class ClearableFileInputWithImagePreview(ClearableFileInput):
%(input)s
</div>"""

def __init__(self, attrs=None, image_preview_template=None,
clear_checkbox_template=None):
if image_preview_template:
self.template_with_initial_and_imagepreview = \
image_preview_template
if clear_checkbox_template:
self.template_with_clear = clear_checkbox_template
super(ClearableFileInputWithImagePreview, self).__init__(attrs)

def get_hidden_field_id(self, name):
i = name.rindex('_')
return "id_%s_%d" % (name[:i], int(name[i + 1:]) + 1)
Expand Down Expand Up @@ -152,12 +143,13 @@ def render(self, name, value, attrs=None):
class SizedImageCenterpointWidgetMixIn(object):

def decompress(self, value):
to_return = [None, None]
if value:
return [
to_return = [
value,
u'x'.join(unicode(num) for num in value.ppoi)
]
return [None, None]
return to_return


class VersatileImagePPOISelectWidget(SizedImageCenterpointWidgetMixIn,
Expand All @@ -183,8 +175,6 @@ def __init__(self, widgets=None, attrs=None, image_preview_template=None):
widgets = (
ClearableFileInputWithImagePreview(
attrs={'class': 'file-chooser'},
image_preview_template=self.image_preview_template or None,
clear_checkbox_template=self.clear_checkbox_template or None
),
HiddenInput(
attrs={'class': 'ppoi-input'}
Expand Down Expand Up @@ -224,7 +214,7 @@ class Media:

class SizedImageCenterpointClickBootstrap3Widget(
VersatileImagePPOIClickWidget):
image_preview_template = """
template_with_initial_and_imagepreview = """
<div class="form-group">
<label>%(initial_text)s</label>
%(initial)s
Expand All @@ -248,8 +238,7 @@ class SizedImageCenterpointClickBootstrap3Widget(
<label class="versatileimagefield-label">%(input_text)s</label>
%(input)s
</div>"""

clear_checkbox_template = (
template_with_clear = (
'<label for="%(clear_checkbox_id)s"'
'class="checkbox-inline">%(clear)s %(clear_checkbox_label)s'
'</label>'
Expand Down

0 comments on commit 1357554

Please sign in to comment.