diff options
| author | Étienne Loks <etienne.loks@peacefrogs.net> | 2013-09-04 20:05:24 +0200 | 
|---|---|---|
| committer | Étienne Loks <etienne.loks@peacefrogs.net> | 2013-09-04 20:05:24 +0200 | 
| commit | 1f16014274a2ad16fcd635fc9b506ef429a33677 (patch) | |
| tree | d7e4c7b4121f09210b398aa4d6bc3830e6e1858e | |
| parent | 4aa9cda8b8bd1c9f51e467541a97d30669130243 (diff) | |
| download | Ishtar-1f16014274a2ad16fcd635fc9b506ef429a33677.tar.bz2 Ishtar-1f16014274a2ad16fcd635fc9b506ef429a33677.zip | |
Improve Image field management (refs #1365)
* add a custom widget to allow display via prettyPhoto on forms
* disable resizing when the image is deleted
* fix "has image" search request to manage empty and null field for images
* fix deletion of files by the wizard
* fix initialization of instancied form for files and images
| -rw-r--r-- | archaeological_finds/forms.py | 3 | ||||
| -rw-r--r-- | ishtar_common/models.py | 2 | ||||
| -rw-r--r-- | ishtar_common/static/js/ishtar.js | 1 | ||||
| -rw-r--r-- | ishtar_common/static/media/style.css | 9 | ||||
| -rw-r--r-- | ishtar_common/views.py | 26 | ||||
| -rw-r--r-- | ishtar_common/widgets.py | 5 | ||||
| -rw-r--r-- | ishtar_common/wizards.py | 11 | 
7 files changed, 43 insertions, 14 deletions
| diff --git a/archaeological_finds/forms.py b/archaeological_finds/forms.py index b72210946..26d180b04 100644 --- a/archaeological_finds/forms.py +++ b/archaeological_finds/forms.py @@ -45,6 +45,7 @@ from ishtar_common.forms_common import get_town_field, \      SourceForm, SourceSelect, SourceDeletionForm, AuthorFormset  from archaeological_context_records.forms import RecordFormSelection +  class FindForm(forms.Form):      file_upload = True      form_label = _("Find") @@ -65,7 +66,7 @@ class FindForm(forms.Form):                       u"(ratio is preserved).</p>") % {                                            'width':settings.IMAGE_MAX_SIZE[0],                                            'height':settings.IMAGE_MAX_SIZE[1]}), -                             required=False) +                             required=False, widget=widgets.ImageFileInput())      def __init__(self, *args, **kwargs):          super(FindForm, self).__init__(*args, **kwargs) diff --git a/ishtar_common/models.py b/ishtar_common/models.py index fb6bebed7..e1ca73a3b 100644 --- a/ishtar_common/models.py +++ b/ishtar_common/models.py @@ -291,7 +291,7 @@ class ImageModel(models.Model):      def save(self, *args, **kwargs):          # manage images -        if self.has_changed('image'): +        if self.has_changed('image') and self.image:              # convert to jpg              filename = os.path.splitext(os.path.split(self.image.name)[-1])[0]              old_path = self.image.path diff --git a/ishtar_common/static/js/ishtar.js b/ishtar_common/static/js/ishtar.js index abd4f6733..71ba78bde 100644 --- a/ishtar_common/static/js/ishtar.js +++ b/ishtar_common/static/js/ishtar.js @@ -48,6 +48,7 @@ $(document).ready(function(){      $('#language_selector').change(function(){          $('#language_form').submit();      }); +    $(".prettyPhoto a").prettyPhoto({'social_tools':''});  });  $('#to_bottom_arrow').live('click', function(){ diff --git a/ishtar_common/static/media/style.css b/ishtar_common/static/media/style.css index a219160f2..cfc75728b 100644 --- a/ishtar_common/static/media/style.css +++ b/ishtar_common/static/media/style.css @@ -74,7 +74,7 @@ h3{      margin:1em 0 0.5em 0;  } -label{display:block} +/*label{display:block}*/  label:first-letter {    text-transform: uppercase; @@ -160,9 +160,10 @@ div#language_form_div{      padding:2px 20px;  } +/*  div#language_form_div label{      display:inline; -} +}*/  div#context_menu{      height:110px; @@ -209,9 +210,9 @@ div#context_menu fieldset{      -webkit-border-radius:8px;      border-radius:8px;  } -div#context_menu fieldset label{ +/*div#context_menu fieldset label{      display:inline; -} +}*/  div#context_menu ul{      margin:0; diff --git a/ishtar_common/views.py b/ishtar_common/views.py index 3ebb20569..cf93ba2a4 100644 --- a/ishtar_common/views.py +++ b/ishtar_common/views.py @@ -36,7 +36,7 @@ from django.contrib.auth import logout  from django.core import serializers  from django.core.exceptions import ObjectDoesNotExist  from django.core.urlresolvers import reverse, NoReverseMatch -from django.db.models import Q +from django.db.models import Q, ImageField  from django.http import HttpResponse, Http404  from django.shortcuts import render_to_response, redirect  from django.template import RequestContext, loader @@ -191,6 +191,7 @@ def get_item(model, func_name, default_name, extra_request_keys=[],          request_keys.update(extra_request_keys)          request_items = request.method == 'POST' and request.POST or request.GET          dct = base_request.copy() +        and_reqs, or_reqs = [], []          try:              old = 'old' in request_items and int(request_items['old'])          except ValueError: @@ -216,6 +217,14 @@ def get_item(model, func_name, default_name, extra_request_keys=[],                      dct[k] = dct[k] == u"2" and True or False                      if k in reversed_bool_fields:                          dct[k] = not dct[k] +                    # check also for empty value with image field +                    c_field = model._meta.get_field(k.split('__')[0]) +                    if k.endswith('__isnull') and \ +                       isinstance(c_field, ImageField): +                        if dct[k]: +                            or_reqs.append((k, {k.split('__')[0]+'__exact':''})) +                        else: +                            dct[k.split('__')[0]+'__regex'] = '.{1}.*'          for k in dated_fields:              if k in dct:                  if not dct[k]: @@ -229,7 +238,6 @@ def get_item(model, func_name, default_name, extra_request_keys=[],                  except AssertionError:                      dct.pop(k)          # manage hierarchic conditions -        or_reqs = []          for req in dct.copy():              for k_hr in HIERARCHIC_FIELDS:                  if type(req) in (list, tuple): @@ -240,7 +248,7 @@ def get_item(model, func_name, default_name, extra_request_keys=[],                              q = Q(**{r:val})                          else:                              q = q | Q(**{r:val}) -                    or_reqs.append(q) +                    and_reqs.append(q)                      break                  elif req.endswith(k_hr + '__pk'):                      val = dct.pop(req) @@ -250,11 +258,16 @@ def get_item(model, func_name, default_name, extra_request_keys=[],                          req = req[:-2] + 'parent__pk'                          q = Q(**{req:val})                          reqs = reqs | q -                    or_reqs.append(reqs) +                    and_reqs.append(reqs)                      break          query = Q(**dct) -        for or_req in or_reqs: -            query = query & or_req +        for k, or_req in or_reqs: +            alt_dct = dct.copy() +            alt_dct.pop(k) +            alt_dct.update(or_req) +            query = query | Q(**alt_dct) +        for and_req in and_reqs: +            query = query & and_req          items = model.objects.filter(query).distinct()          q = request_items.get('sidx') @@ -571,7 +584,6 @@ def action(request, action_slug, obj_id=None, *args, **kwargs):      associated_wizard = action_slug + '_wizard'      dct = {}      globals_dct = globals() -    print action_slug      if action_slug in globals_dct:          return globals_dct[action_slug](request, dct, obj_id, *args, **kwargs)      elif hasattr(ishtar_forms, action_slug + "_wizard"): diff --git a/ishtar_common/widgets.py b/ishtar_common/widgets.py index 94d7f709a..a97cfe70b 100644 --- a/ishtar_common/widgets.py +++ b/ishtar_common/widgets.py @@ -23,6 +23,7 @@ from django import forms  from django.conf import settings
  from django.core.urlresolvers import resolve, reverse
  from django.db.models import fields
 +from django.forms import ClearableFileInput
  from django.forms.widgets import flatatt
  from django.template import Context, loader
  from django.utils.encoding import smart_unicode
 @@ -42,6 +43,10 @@ class DeleteWidget(forms.CheckboxInput):          output.append('</td></tr>')
          return mark_safe('\n'.join(output))
 +class ImageFileInput(ClearableFileInput):
 +    template_with_initial = u'<span class="prettyPhoto">%(initial)s</span>'\
 +                      u' %(clear_template)s<br />%(input_text)s: %(input)s'
 +
  class SquareMeterWidget(forms.TextInput):
      def render(self, name, value, attrs=None):
          if not value:
 diff --git a/ishtar_common/wizards.py b/ishtar_common/wizards.py index e1f031818..b96e33669 100644 --- a/ishtar_common/wizards.py +++ b/ishtar_common/wizards.py @@ -22,6 +22,8 @@ import datetime  from django.conf import settings  from django.contrib.formtools.wizard.views import NamedUrlWizardView  from django.core.exceptions import ObjectDoesNotExist +from django.core.files.images import ImageFile +from django.db.models.fields.files import FileField  from django.shortcuts import render_to_response  from django.template import RequestContext  from django.utils.datastructures import MultiValueDict @@ -334,6 +336,11 @@ class Wizard(NamedUrlWizardView):              for k in dct:                  if k.startswith('pk'):                      continue +                # False set to None for images and files +                if isinstance(obj.__class__._meta.get_field(k), FileField) or\ +                   isinstance(obj.__class__._meta.get_field(k), ImageFile): +                    if not dct[k]: +                        dct[k] = None                  setattr(obj, k, dct[k])              try:                  obj.full_clean() @@ -646,7 +653,9 @@ class Wizard(NamedUrlWizardView):                      continue                  if hasattr(value, 'pk'):                      value = value.pk -                if value in (True, False): +                if value in (True, False) or \ +                   isinstance(value, FileField) or \ +                   isinstance(value, ImageFile):                      initial[base_field] = value                  elif value != None:                      initial[base_field] = unicode(value) | 
