diff options
Diffstat (limited to 'ishtar_common/widgets.py')
| -rw-r--r-- | ishtar_common/widgets.py | 71 | 
1 files changed, 35 insertions, 36 deletions
diff --git a/ishtar_common/widgets.py b/ishtar_common/widgets.py index 37f44e938..3d69ff117 100644 --- a/ishtar_common/widgets.py +++ b/ishtar_common/widgets.py @@ -33,7 +33,7 @@ from django.forms.widgets import CheckboxSelectMultiple as \      CheckboxSelectMultipleBase, NumberInput  from django.template import loader  from django.template.defaultfilters import slugify -from django.utils.encoding import smart_unicode +from django.utils.encoding import smart_text  from django.utils.functional import lazy  from django.utils.html import escape  from django.utils.safestring import mark_safe @@ -44,7 +44,7 @@ from ishtar_common import models  logger = logging.getLogger(__name__) -reverse_lazy = lazy(reverse, unicode) +reverse_lazy = lazy(reverse, str)  class SelectReadonly(forms.Select): @@ -66,7 +66,7 @@ class SelectReadonly(forms.Select):              if hasattr(self.model, 'verbose_name'):                  label = i.verbose_name              else: -                label = unicode(i) +                label = str(i)              yield (i.pk, label)      def render(self, name, value, attrs=None, choices=()): @@ -141,7 +141,7 @@ class Select2Dynamic(Select2Media, forms.Select):              u"tags: true",          ]          ''' -        msg = unicode( +        msg = str(              _(u"Are you sure you want to add this term? (the addition is "                u"effective after registration of the element)")          ) @@ -198,10 +198,10 @@ class Select2Base(Select2Media):      def get_choices(self):          for i in self.get_q().all(): -            yield (i.pk, unicode(i)) +            yield (i.pk, str(i))      def render(self, name, value, attrs=None, choices=()): -        self.remote = unicode(self.remote) +        self.remote = str(self.remote)          if self.remote in ('None', 'false'):              # test on lazy object is buggy... so we have this ugly test              self.remote = None @@ -300,7 +300,7 @@ class CheckboxSelectMultiple(CheckboxSelectMultipleBase):      TODO: test and remove (test case: treatment type not keep on modif)      """      def render(self, name, value, attrs=None, choices=()): -        if type(value) in (str, unicode): +        if type(value) in (str, str):              value = value.split(',')          if not isinstance(value, (list, tuple)):              value = [value] @@ -422,16 +422,16 @@ class ImageFileInput(ClearableFileInput):              return value          # try to display posted images          if hasattr(value, 'file'): -            full_path = unicode(value.file) +            full_path = str(value.file)              if full_path.startswith(settings.MEDIA_ROOT):                  value.url = settings.MEDIA_URL + full_path[                                                   len(settings.MEDIA_ROOT):]          elif value: -            full_path = settings.MEDIA_ROOT + unicode(value) +            full_path = settings.MEDIA_ROOT + str(value)              try:                  with open(full_path) as f:                      f = File(f) -                    f.url = settings.MEDIA_URL + unicode(value) +                    f.url = settings.MEDIA_URL + str(value)                      value = f              except IOError:                  return value @@ -553,7 +553,7 @@ class ModelFieldMixin(object):                  values.append(self.model.objects.get(pk=v))              except self.model.DoesNotExist:                  raise ValidationError( -                    unicode( +                    str(                          _(u"{} is not a valid key for {}")                      ).format(v, self.model)                  ) @@ -620,18 +620,18 @@ class JQueryAutoComplete(forms.TextInput):          v = data.get(name, None)          if not self.multiple:              return data.get(name, None) -        if type(v) == unicode and "," in v: +        if type(v) == str and "," in v:              return [item.strip() for item in v.split(',') if item.strip()]          return data.getlist(name, None)      def render_js(self, field_id):          if isinstance(self.source, list):              source = JSONEncoder().encode(self.source) -        elif isinstance(self.source, str) or isinstance(self.source, unicode): +        elif isinstance(self.source, str) or isinstance(self.source, str):              source = "'%s'" % escape(self.source)          else:              try: -                source = "'" + unicode(self.source) + "'" +                source = "'" + str(self.source) + "'"              except:                  raise ValueError('source type is not valid')          dynamic_limit = [ @@ -660,7 +660,7 @@ class JQueryAutoComplete(forms.TextInput):              hiddens = []              selects = []              if type(value) not in (list, tuple): -                values = unicode(escape(smart_unicode(value))) +                values = str(escape(smart_text(value)))                  values = values.replace('[', '').replace(']', '')                  values = values.split(',')              else: @@ -674,7 +674,7 @@ class JQueryAutoComplete(forms.TextInput):                  selects.append(v)                  if self.associated_model:                      try: -                        selects[-1] = unicode( +                        selects[-1] = str(                              self.associated_model.objects.get(pk=v))                      except (self.associated_model.DoesNotExist, ValueError):                          selects.pop() @@ -703,7 +703,7 @@ class JQueryAutoComplete(forms.TextInput):              limits = []              for k in self.limit:                  limits.append(k + "__" + "-".join( -                              [unicode(v) for v in self.limit[k]])) +                              [str(v) for v in self.limit[k]]))              args = [attrs_select['id']]              if limits:                  args.append(';'.join(limits)) @@ -770,15 +770,14 @@ class JQueryTown(forms.TextInput):      def encode_source(cls, source):          if isinstance(source, list):              encoded_src = JSONEncoder().encode(source) -        elif isinstance(source, str) \ -                or isinstance(source, unicode): +        elif isinstance(source, str):              src = escape(source)              if not src.endswith('/'):                  src += "/"              encoded_src = "'%s'" % src          else:              try: -                src = unicode(source) +                src = str(source)                  if not src.endswith('/'):                      src += "/"                  encoded_src = "'%s'" % src @@ -797,7 +796,7 @@ class JQueryTown(forms.TextInput):              hiddens = []              selects = []              if type(value) not in (list, tuple): -                values = unicode(escape(smart_unicode(value))) +                values = str(escape(smart_text(value)))                  values = values.replace('[', '').replace(']', '')                  values = values.split(',')              else: @@ -811,7 +810,7 @@ class JQueryTown(forms.TextInput):                  selects.append(v)                  try:                      item = models.Town.objects.get(pk=v) -                    selects[-1] = unicode(item) +                    selects[-1] = str(item)                      if item.departement:                          selected_department = item.departement.number                          if item.departement.state: @@ -879,11 +878,11 @@ class JQueryPersonOrganization(forms.TextInput):          if isinstance(source, list):              encoded_src = JSONEncoder().encode(source)          elif isinstance(source, str) \ -                or isinstance(source, unicode): +                or isinstance(source, str):              encoded_src = "'%s'" % escape(source)          else:              try: -                encoded_src = "'" + unicode(source) + "'" +                encoded_src = "'" + str(source) + "'"              except:                  raise ValueError('source type is not valid')          return encoded_src @@ -910,7 +909,7 @@ class JQueryPersonOrganization(forms.TextInput):              hiddens = []              selects = []              if type(value) not in (list, tuple): -                values = unicode(escape(smart_unicode(value))) +                values = str(escape(smart_text(value)))                  values = values.replace('[', '').replace(']', '')                  values = values.split(',')              else: @@ -925,7 +924,7 @@ class JQueryPersonOrganization(forms.TextInput):                  if self.model:                      try:                          item = self.model.objects.get(pk=v) -                        selects[-1] = unicode(item) +                        selects[-1] = str(item)                          selected = item.pk                      except (self.model.DoesNotExist, ValueError):                          selects.pop() @@ -1036,16 +1035,16 @@ class DataTable(Select2Media, forms.RadioSelect):                      field_name += col_name[len(self.col_prefix):]                  else:                      field_name += col_name -                field_verbose_names.append(unicode(field_verbose_name)) +                field_verbose_names.append(str(field_verbose_name))              if not field_name:                  field_name = "__".join(col_names)              if field_name in col_labels:                  lbl = col_labels[field_name]                  if callable(lbl):                      lbl = lbl() -                jq_col_names.append(unicode(lbl)) +                jq_col_names.append(str(lbl))              elif col_names and col_names[0] in col_labels: -                jq_col_names.append(unicode(col_labels[col_names[0]])) +                jq_col_names.append(str(col_labels[col_names[0]]))              else:                  jq_col_names.append(settings.JOINT.join(                      [f for f in field_verbose_names if f])) @@ -1078,14 +1077,14 @@ class DataTable(Select2Media, forms.RadioSelect):          dct['encoding'] = settings.ENCODING or 'utf-8'          try: -            dct['source'] = unicode(self.source) +            dct['source'] = str(self.source)          except NoReverseMatch:              logger.warning('Cannot resolve source for {} widget'.format(                  self.form))          # full CSV export currently disabled -        #if unicode(self.source_full) and unicode(self.source_full) != 'None': -        #    dct['source_full'] = unicode(self.source_full) +        #if str(self.source_full) and str(self.source_full) != 'None': +        #    dct['source_full'] = str(self.source_full)          dct['extra_sources'] = []          dct['quick_actions'] = [] @@ -1102,15 +1101,15 @@ class DataTable(Select2Media, forms.RadioSelect):              if hasattr(self.associated_model, "QUICK_ACTIONS"):                  dct['quick_actions'] = \                      self.associated_model.get_quick_actions(user=self.user) -        source = unicode(self.source) +        source = str(self.source)          dct.update({'name': name,                      'col_names': col_names,                      'extra_cols': extra_cols,                      'source': source,                      'col_idx': col_idx, -                    'no_result': unicode(_("No results")), -                    'loading': unicode(_("Loading...")), -                    'remove': unicode(_(u"Remove")), +                    'no_result': str(_("No results")), +                    'loading': str(_("Loading...")), +                    'remove': str(_(u"Remove")),                      'sname': name.replace('-', ''),                      'gallery': self.gallery,                      'use_map': self.map() if callable(self.map) else self.map,  | 
