From e87527a2c4626aba21a3a775a237c9dda2a86238 Mon Sep 17 00:00:00 2001
From: Emmanuel Cazenave <ecazenave@entrouvert.com>
Date: Thu, 11 Jul 2019 15:35:59 +0200
Subject: [PATCH] add compatiblity with django 1.11  (#21145)

---
 debian/control               |  4 +-
 django_journal/__init__.py   | 75 ------------------------------------
 django_journal/admin.py      | 10 ++---
 django_journal/journal.py    | 74 +++++++++++++++++++++++++++++++++++
 django_journal/middleware.py |  7 ++--
 django_journal/models.py     |  4 +-
 setup.py                     |  2 +-
 tests/test_main.py           |  2 +-
 tox.ini                      |  4 +-
 9 files changed, 91 insertions(+), 91 deletions(-)
 create mode 100644 django_journal/journal.py

diff --git a/debian/control b/debian/control
index 4370e63..77f380f 100644
--- a/debian/control
+++ b/debian/control
@@ -3,7 +3,7 @@ Maintainer: Entr'ouvert <info@entrouvert.com>
 Section: python
 Priority: optional
 Build-Depends: python-setuptools (>= 0.6b3), python-all (>= 2.6), debhelper (>= 7.4.3),
- python-django (>= 1.5)
+ python-django (>= 1.8)
 Standards-Version: 3.9.1
 X-Python-Version: >= 2.7
 
@@ -11,7 +11,7 @@ Package: python-django-journal
 Architecture: all
 Depends: ${misc:Depends},
     python (>= 2.6),
-    python-django (>= 1.5),
+    python-django (>= 1.8),
     python-django-model-utils
 Description: Django application to keep a structured -- i.e. not just log
  strings -- journal of events in your project
diff --git a/django_journal/__init__.py b/django_journal/__init__.py
index 6b0f23e..e69de29 100644
--- a/django_journal/__init__.py
+++ b/django_journal/__init__.py
@@ -1,75 +0,0 @@
-import logging
-
-from exceptions import JournalException
-from models import (Journal, Tag, Template)
-
-import django.db.models
-from django.conf import settings
-
-from decorator import atomic
-
-__all__ = ('record', 'error_record', 'Journal')
-
-
-def unicode_truncate(s, length, encoding='utf-8'):
-    '''Truncate an unicode string so that its UTF-8 encoding is less than
-       length.'''
-    encoded = s.encode(encoding)[:length]
-    return encoded.decode(encoding, 'ignore')
-
-@atomic
-def record(tag, template, using=None, **kwargs):
-    '''Record an event in the journal. The modification is done inside the
-       current transaction.
-
-       tag:
-           a string identifier giving the type of the event
-       tpl:
-           a format string to describe the event
-       kwargs:
-           a mapping of object or data to interpolate in the format string
-    '''
-    template = unicode(template)
-    tag = Tag.objects.using(using).get_cached(name=tag)
-    template = Template.objects.using(using).get_cached(content=template)
-    try:
-        message = template.content.format(**kwargs)
-    except (KeyError, IndexError), e:
-        raise JournalException(
-                'Missing variable for the template message', template, e)
-    try:
-        logger = logging.getLogger('django.journal.%s' % tag)
-        if tag.name == 'error' or tag.name.startswith('error-'):
-            logger.error(message)
-        elif tag.name == 'warning' or tag.name.startswith('warning-'):
-            logger.warning(message)
-        else:
-            logger.info(message)
-    except:
-        try:
-            logging.getLogger('django.journal').exception('Unable to log msg')
-        except:
-            pass # we tried, really, we tried
-    journal = Journal.objects.using(using).create(tag=tag, template=template,
-            message=unicode_truncate(message, 128))
-    for name, value in kwargs.iteritems():
-        if value is None:
-            continue
-        tag = Tag.objects.using(using).get_cached(name=name)
-        if isinstance(value, django.db.models.Model):
-            journal.objectdata_set.create(tag=tag, content_object=value)
-        else:
-            journal.stringdata_set.create(tag=tag, content=unicode(value))
-    return journal
-
-def error_record(tag, tpl, **kwargs):
-    '''Records error events.
-
-       You must use this function when logging error events. It uses another
-       database alias than the default one to be immune to transaction rollback
-       when logging in the middle of a transaction which is going to
-       rollback.
-    '''
-    if kwargs.get('using') is None:
-        kwargs['using'] = getattr(settings, 'JOURNAL_DB_FOR_ERROR_ALIAS', 'default')
-    return record(tag, tpl, **kwargs)
diff --git a/django_journal/admin.py b/django_journal/admin.py
index faead5f..848f553 100644
--- a/django_journal/admin.py
+++ b/django_journal/admin.py
@@ -3,15 +3,13 @@ from string import Formatter
 import django.contrib.admin as admin
 from django.contrib.contenttypes.models import ContentType
 from django.utils.html import escape
-
-from models import Journal, Tag, ObjectData, StringData
-
 from django.db import models
 from django.utils.translation import ugettext_lazy as _
-from django.utils.html import escape
 from django.core.urlresolvers import reverse, NoReverseMatch
 
-import actions
+from .models import Journal, Tag, ObjectData, StringData
+from .actions import export_as_csv
+
 
 class ModelAdminFormatter(Formatter):
     def __init__(self, model_admin=None, filter_link=True,
@@ -71,7 +69,7 @@ class JournalAdmin(admin.ModelAdmin):
     )
     date_hierarchy = 'time'
     search_fields = ('message','tag__name','time')
-    actions = [ actions.export_as_csv ]
+    actions = [ export_as_csv ]
 
     class Media:
         css = {
diff --git a/django_journal/journal.py b/django_journal/journal.py
new file mode 100644
index 0000000..cb69d28
--- /dev/null
+++ b/django_journal/journal.py
@@ -0,0 +1,74 @@
+import logging
+
+from django.conf import settings
+import django.db.models
+
+from .decorator import atomic
+from .exceptions import JournalException
+from .models import Journal, Tag, Template
+
+
+def unicode_truncate(s, length, encoding='utf-8'):
+    '''Truncate an unicode string so that its UTF-8 encoding is less than
+       length.'''
+    encoded = s.encode(encoding)[:length]
+    return encoded.decode(encoding, 'ignore')
+
+
+@atomic
+def record(tag, template, using=None, **kwargs):
+    '''Record an event in the journal. The modification is done inside the
+       current transaction.
+
+       tag:
+           a string identifier giving the type of the event
+       tpl:
+           a format string to describe the event
+       kwargs:
+           a mapping of object or data to interpolate in the format string
+    '''
+    template = unicode(template)
+    tag = Tag.objects.using(using).get_cached(name=tag)
+    template = Template.objects.using(using).get_cached(content=template)
+    try:
+        message = template.content.format(**kwargs)
+    except (KeyError, IndexError), e:
+        raise JournalException(
+                'Missing variable for the template message', template, e)
+    try:
+        logger = logging.getLogger('django.journal.%s' % tag)
+        if tag.name == 'error' or tag.name.startswith('error-'):
+            logger.error(message)
+        elif tag.name == 'warning' or tag.name.startswith('warning-'):
+            logger.warning(message)
+        else:
+            logger.info(message)
+    except:
+        try:
+            logging.getLogger('django.journal').exception('Unable to log msg')
+        except:
+            pass # we tried, really, we tried
+    journal = Journal.objects.using(using).create(tag=tag, template=template,
+            message=unicode_truncate(message, 128))
+    for name, value in kwargs.iteritems():
+        if value is None:
+            continue
+        tag = Tag.objects.using(using).get_cached(name=name)
+        if isinstance(value, django.db.models.Model):
+            journal.objectdata_set.create(tag=tag, content_object=value)
+        else:
+            journal.stringdata_set.create(tag=tag, content=unicode(value))
+    return journal
+
+
+def error_record(tag, tpl, **kwargs):
+    '''Records error events.
+
+       You must use this function when logging error events. It uses another
+       database alias than the default one to be immune to transaction rollback
+       when logging in the middle of a transaction which is going to
+       rollback.
+    '''
+    if kwargs.get('using') is None:
+        kwargs['using'] = getattr(settings, 'JOURNAL_DB_FOR_ERROR_ALIAS', 'default')
+    return record(tag, tpl, **kwargs)
diff --git a/django_journal/middleware.py b/django_journal/middleware.py
index 8b7ea51..40cc0d1 100644
--- a/django_journal/middleware.py
+++ b/django_journal/middleware.py
@@ -1,4 +1,5 @@
-import django_journal
+from django_journal import journal
+
 
 class JournalMiddleware(object):
     '''Add record and error_record methods to the request object to log
@@ -15,13 +16,13 @@ class JournalMiddleware(object):
                 kwargs['user'] = user
             if 'ip' not in kwargs:
                 kwargs['ip'] = ip
-            django_journal.record(tag, template, using=using,**kwargs)
+            journal.record(tag, template, using=using,**kwargs)
         def error_record(tag, template, using=None, **kwargs):
             if 'user' not in kwargs:
                 kwargs['user'] = user
             if 'ip' not in kwargs:
                 kwargs['ip'] = ip
-            django_journal.error_record(tag, template, using=using, **kwargs)
+            journal.error_record(tag, template, using=using, **kwargs)
         request.record = record
         request.error_record = error_record
         return None
diff --git a/django_journal/models.py b/django_journal/models.py
index c711722..a39a25b 100644
--- a/django_journal/models.py
+++ b/django_journal/models.py
@@ -1,7 +1,7 @@
 import string
 
 from django.db import models
-from django.contrib.contenttypes import generic
+from django.contrib.contenttypes.fields import GenericForeignKey
 from django.utils.translation import ugettext_lazy as _
 
 import managers
@@ -143,7 +143,7 @@ class ObjectData(models.Model):
             verbose_name=_('content type'))
     object_id = models.PositiveIntegerField(db_index=True,
             verbose_name=_('object id'))
-    content_object = generic.GenericForeignKey('content_type',
+    content_object = GenericForeignKey('content_type',
             'object_id')
 
     class Meta:
diff --git a/setup.py b/setup.py
index a31d5d3..f5747ed 100755
--- a/setup.py
+++ b/setup.py
@@ -116,6 +116,6 @@ setup(name='django-journal',
           'test': test
       },
       install_requires=[
-          'django >= 1.7,<1.9',
+          'django >= 1.8,<2.0',
           'django-model-utils',
       ])
diff --git a/tests/test_main.py b/tests/test_main.py
index c8a3d05..20a70c6 100644
--- a/tests/test_main.py
+++ b/tests/test_main.py
@@ -3,7 +3,7 @@ from django.contrib.auth.models import User, Group
 from django.db import transaction
 
 
-from django_journal import record, error_record
+from django_journal.journal import record, error_record
 from django_journal.actions import export_as_csv_generator
 from django_journal.models import Journal
 
diff --git a/tox.ini b/tox.ini
index b6dffb0..365c5da 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,12 +1,14 @@
 [tox]
 toxworkdir = /tmp/tox-{env:USER}/django-journal/{env:BRANCH_NAME:}
-envlist = py2-coverage
+envlist = py2-coverage-{django111,django18}
 
 
 [testenv]
 basepython = python2
 usedevelop = True
 deps =
+  django18: django<1.9
+  django111: django<2
   psycopg2
   pytest-cov
   pytest
-- 
2.20.1

