From d4bd4a0d3099fa81b3ed58b9b6a53e734e2795e5 Mon Sep 17 00:00:00 2001 From: Tim Valenta Date: Wed, 23 Jul 2014 13:22:12 -0700 Subject: [PATCH] Remove traces of StrAndUnicode This shift brings us closer to a Python3-first code base. --- datatableview/compat.py | 19 +++++++++++++++++++ datatableview/utils.py | 16 ++++++---------- 2 files changed, 25 insertions(+), 10 deletions(-) create mode 100644 datatableview/compat.py diff --git a/datatableview/compat.py b/datatableview/compat.py new file mode 100644 index 00000000..57824757 --- /dev/null +++ b/datatableview/compat.py @@ -0,0 +1,19 @@ +""" Backports of code left behind by new versions of Django. """ + +import six + +# Django 1.7 removed StrAndUnicode, so it has been purged from this project as well. To bridge the +# gap, we will rely on this utility directly, instead of trying to generate our own replacement +# StrAndUnicode class. +def python_2_unicode_compatible(klass): + """ + A decorator that defines __unicode__ and __str__ methods under Python 2. + Under Python 3 it does nothing. + + To support Python 2 and 3 with a single code base, define a __str__ method + returning text and apply this decorator to the class. + """ + if not six.PY3: + klass.__unicode__ = klass.__str__ + klass.__str__ = lambda self: self.__unicode__().encode('utf-8') + return klass diff --git a/datatableview/utils.py b/datatableview/utils.py index daa0b3f2..2f1b93ed 100644 --- a/datatableview/utils.py +++ b/datatableview/utils.py @@ -10,17 +10,12 @@ from django.db.models.fields import FieldDoesNotExist from django.template.loader import render_to_string +from django.forms.util import flatatt try: - from django.utils.encoding import StrAndUnicode -except ImportError: from django.utils.encoding import python_2_unicode_compatible - @python_2_unicode_compatible - class StrAndUnicode: - def __str__(self): - return self.code - -from django.forms.util import flatatt +except ImportError: + from .compat import python_2_unicode_compatible import six @@ -155,7 +150,8 @@ def get_field_definition(field_definition): return FieldDefinitionTuple(*field) -class DatatableStructure(StrAndUnicode): +@python_2_unicode_compatible +class DatatableStructure(object): """ A class designed to be echoed directly to into template HTML to represent a skeleton table structure that datatables.js can use. @@ -177,7 +173,7 @@ def __init__(self, ajax_url, options, model=None): sort_direction = 'desc' if name[0] == '-' else 'asc' self.ordering[plain_name] = ColumnOrderingTuple(i, index, sort_direction) - def __unicode__(self): + def __str__(self): return render_to_string(self.options['structure_template'], { 'url': self.url, 'result_counter_id': self.options['result_counter_id'],