From 099a9fa3dda444ceb0b0e9996c15dc529d75f838 Mon Sep 17 00:00:00 2001 From: Alon Hammerman Date: Tue, 10 Sep 2013 19:35:34 -0500 Subject: [PATCH] Make CloudinaryInput extend ClearableFileInput and behave more like it --- cloudinary/__init__.py | 1 + cloudinary/forms.py | 25 ++++++++++++++++++++----- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/cloudinary/__init__.py b/cloudinary/__init__.py index 0837d18f..e97384ef 100644 --- a/cloudinary/__init__.py +++ b/cloudinary/__init__.py @@ -7,6 +7,7 @@ OLD_AKAMAI_SHARED_CDN = "cloudinary-a.akamaihd.net" AKAMAI_SHARED_CDN = "res.cloudinary.com" SHARED_CDN = AKAMAI_SHARED_CDN +UPLOAD_FIELD_NAME = "file" from cloudinary import utils diff --git a/cloudinary/forms.py b/cloudinary/forms.py index c1a75725..e23fb141 100644 --- a/cloudinary/forms.py +++ b/cloudinary/forms.py @@ -1,5 +1,6 @@ from django import forms -from cloudinary import CloudinaryImage +from django.forms import widgets +from cloudinary import CloudinaryImage, UPLOAD_FIELD_NAME import cloudinary.uploader import cloudinary.utils import re @@ -11,8 +12,8 @@ def cl_init_js_callbacks(form, request): if (isinstance(field, CloudinaryJsFileField)): field.enable_callback(request) -class CloudinaryInput(forms.TextInput): - input_type = 'file' +class CloudinaryInput(forms.ClearableFileInput): + template_with_initial = u'%(initial_text)s: %(initial)s %(clear_template)s
%(input_text)s: %(input)s' def render(self, name, value, attrs=None): self.build_attrs(attrs) @@ -29,10 +30,24 @@ def render(self, name, value, attrs=None): attrs["data-cloudinary-field"] = name attrs["class"] = " ".join(["cloudinary-fileupload", self.attrs.get("class", "")]) - return super(CloudinaryInput, self).render("file", None, attrs=attrs) + return super(CloudinaryInput, self).render(UPLOAD_FIELD_NAME, value, attrs=attrs) + # From django.forms.widgets.ClearableFileInput + def value_from_datadict(self, data, files, name): + upload = widgets.Widget().value_from_datadict(data, files, name) + if not self.is_required and widgets.CheckboxInput().value_from_datadict( + data, files, self.clear_checkbox_name(name)): + if upload: + # If the user contradicts themselves (uploads a new file AND + # checks the "clear" checkbox), we return a unique marker + # object that FileField will turn into a ValidationError. + return widgets.FILE_INPUT_CONTRADICTION + # False signals to clear any existing value, as opposed to just None + return False + return upload -class CloudinaryJsFileField(forms.Field): + +class CloudinaryJsFileField(forms.FileField): default_error_messages = { 'required': _(u"No image selected!") }