[Python-modules-commits] [django-reversion] 01/07: Import django-reversion_1.10.2.orig.tar.gz

Michael Fladischer fladi at moszumanska.debian.org
Fri Apr 22 20:43:19 UTC 2016


This is an automated email from the git hooks/post-receive script.

fladi pushed a commit to branch master
in repository django-reversion.

commit 84e698bf83ced2e70fb3cbad750746143666b346
Author: Michael Fladischer <FladischerMichael at fladi.at>
Date:   Fri Apr 22 22:24:49 2016 +0200

    Import django-reversion_1.10.2.orig.tar.gz
---
 .travis.yml                                        |  22 +---
 CHANGELOG.md                                       |  16 ++-
 MANIFEST.in                                        |   1 +
 README.rst                                         |   4 +-
 docs/admin.rst                                     |   4 +
 docs/api.rst                                       |  86 +++++++-------
 docs/conf.py                                       |   2 +-
 docs/diffs.rst                                     |   3 +-
 docs/django-versions.rst                           |   4 +-
 docs/how-it-works.rst                              |   8 +-
 setup.py                                           |   3 +-
 src/reversion/__init__.py                          |   2 +-
 src/reversion/admin.py                             |  31 +++--
 .../management/commands/createinitialrevisions.py  |  67 ++++-------
 .../management/commands/deleterevisions.py         |  66 +++++------
 src/reversion/models.py                            |   2 +
 src/reversion/revisions.py                         |  18 +--
 src/reversion/south_migrations/0001_initial.py     | 104 ----------------
 .../0002_auto__add_field_version_type.py           |  77 ------------
 .../0003_auto__add_field_version_object_id_int.py  |  79 -------------
 .../0004_populate_object_id_int.py                 |  89 --------------
 .../0005_auto__add_field_revision_manager_slug.py  |  80 -------------
 .../0006_remove_delete_revisions.py                |  77 ------------
 .../0007_auto__del_field_version_type.py           |  80 -------------
 .../0008_auto__add_index_revision_date_created.py  |  78 ------------
 src/reversion/south_migrations/__init__.py         |   0
 src/tests/test_reversion/admin.py                  |  23 +++-
 src/tests/test_reversion/models.py                 |  12 ++
 src/tests/test_reversion/tests.py                  | 131 ++++++++++++---------
 29 files changed, 275 insertions(+), 894 deletions(-)

diff --git a/.travis.yml b/.travis.yml
index a53859a..f6c55e7 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -8,24 +8,14 @@ cache:
   directories:
     - $HOME/.cache/pip
 env:
-  - DJANGO=django==1.7.11
-  - DJANGO=django==1.7.11 DB_ENGINE="django.db.backends.postgresql_psycopg2" DB_NAME="test_project" DB_USER="postgres"
-  - DJANGO=django==1.7.11 DB_ENGINE="django.db.backends.mysql" DB_NAME="test_project" DB_USER="travis"
-  - DJANGO=django==1.8.7
-  - DJANGO=django==1.8.7 DB_ENGINE="django.db.backends.postgresql_psycopg2" DB_NAME="test_project" DB_USER="postgres"
-  - DJANGO=django==1.8.7 DB_ENGINE="django.db.backends.mysql" DB_NAME="test_project" DB_USER="travis"
-  - DJANGO=django==1.9.0
-  - DJANGO=django==1.9.0 DB_ENGINE="django.db.backends.postgresql" DB_NAME="test_project" DB_USER="postgres"
-  - DJANGO=django==1.9.0 DB_ENGINE="django.db.backends.mysql" DB_NAME="test_project" DB_USER="travis"
+  - DJANGO=django==1.8.8
+  - DJANGO=django==1.8.8 DB_ENGINE="django.db.backends.postgresql_psycopg2" DB_NAME="test_project" DB_USER="postgres"
+  - DJANGO=django==1.8.8 DB_ENGINE="django.db.backends.mysql" DB_NAME="test_project" DB_USER="travis"
+  - DJANGO=django==1.9.2
+  - DJANGO=django==1.9.2 DB_ENGINE="django.db.backends.postgresql" DB_NAME="test_project" DB_USER="postgres"
+  - DJANGO=django==1.9.2 DB_ENGINE="django.db.backends.mysql" DB_NAME="test_project" DB_USER="travis"
 matrix:
   fast_finish: true
-  exclude:
-    - python: 3.5
-      env: DJANGO=django==1.7.11
-    - python: 3.5
-      env: DJANGO=django==1.7.11 DB_ENGINE="django.db.backends.postgresql_psycopg2" DB_NAME="test_project" DB_USER="postgres"
-    - python: 3.5
-      env: DJANGO=django==1.7.11 DB_ENGINE="django.db.backends.mysql" DB_NAME="test_project" DB_USER="travis"
 services:
   - postgresql
   - mysql
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f238213..55840bc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,18 @@
 # django-reversion changelog
 
 
+## 1.10.2 - 18/04/2016
+
+- Fixing deprecation warnings (@claudep).
+- Minor tweaks and bug fixes (@fladi, @claudep, @etianen).
+
+
+## 1.10.1 - 27/01/2016
+
+- Fixing some deprecation warnings (@ticosax).
+- Minor tweaks (@claudep, @etianen).
+
+
 ## 1.10 - 02/12/2015
 
 - **Breaking:** Updated the location of [admin classes](http://django-reversion.readthedocs.org/en/latest/admin.html).
@@ -46,10 +58,10 @@
 
     ```py
     # New-style import for accesssing the low-level API.
-    from reversion import revisions
+    from reversion import revisions as reversion
 
     # Use low-level API methods from the revisions namespace.
-    @revisions.register
+    @reversion.register
     class YourModel(models.Model):
         ...
     ```
diff --git a/MANIFEST.in b/MANIFEST.in
index 258e5e9..461e8e1 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -5,4 +5,5 @@ include README.rst
 include CHANGELOG.md
 include MANIFEST.in
 recursive-include docs *
+recursive-include src/tests *.py
 prune docs/_build
diff --git a/README.rst b/README.rst
index ddd41ec..e61b701 100644
--- a/README.rst
+++ b/README.rst
@@ -38,9 +38,7 @@ Upgrading
 
 If you're upgrading your existing installation of django-reversion, please check
 the `Schema Migrations <http://django-reversion.readthedocs.org/en/latest/migrations.html>`_
-documentation for information on any database changes and how to upgrade. If you're using
-South to manage database migrations in your project, then upgrading is as easy as running
-a few django management commands.
+documentation for information on any database changes and how to upgrade.
 
 It's always worth checking the `CHANGELOG <https://github.com/etianen/django-reversion/blob/master/CHANGELOG.md>`_
 before upgrading too, just in case you get caught off-guard by a minor upgrade to the library.
diff --git a/docs/admin.rst b/docs/admin.rst
index 24cfb44..ef83ff0 100644
--- a/docs/admin.rst
+++ b/docs/admin.rst
@@ -15,6 +15,10 @@ django-reversion can be used to add a powerful rollback and recovery facility to
 
     admin.site.register(YourModel, YourModelAdmin)
 
+**Note:** If you've registered your models explicitly using the :ref:`low level API <api>`, then the admin class will honour the
+configuration you specify there. Otherwise, the admin class will auto-register your model, following all inline model relations
+and parent superclasses.
+
 You can also use ``VersionAdmin`` as a mixin with another specialized admin class.
 
 ::
diff --git a/docs/api.rst b/docs/api.rst
index 54c3bd0..5b41bc8 100644
--- a/docs/api.rst
+++ b/docs/api.rst
@@ -13,39 +13,35 @@ Import the low-level API as follows:
 
 ::
 
-    from reversion import revisions
+    from reversion import revisions as reversion
 
-**Note:** If using django-reversion < 1.10, import the low-level API using ``import reversion as revisions``.
+**Note:** If using django-reversion < 1.10, import the low-level API using ``import reversion``.
 
 
 Registering models with django-reversion
 ----------------------------------------
 
-If you're already using the :ref:`admin integration <admin>` for a model, then there's no need to register it. However, if you want to register a model without using the admin integration, then you need to use the ``revisions.register()`` method.
+If you're already using the :ref:`admin integration <admin>` for a model, then there's no need to register it. However, if you want to register a model without using the admin integration, then you need to use the ``reversion.register()`` method.
 
 ::
 
-    from reversion import revisions
+    reversion.register(YourModel)
 
-    revisions.register(YourModel)
-
-``revisions.register`` can also be used as a class decorator, with or without arguments.
+``reversion.register`` can also be used as a class decorator, with or without arguments.
 
 ::
 
-    from reversion import revisions
-
-    @revisions.register
+    @reversion.register()
     class YourModel(models.Model):
         ...
 
-    @revisions.register(format='yaml')
+    @reversion.register(format='yaml')
     class YourOtherModel(models.Model):
         ...
 
 **Warning:** If you’re using django-reversion in a management command, and are using the automatic ``VersionAdmin`` registration method, then you’ll need to import the relevant ``admin.py`` file at the top of your management command file.
 
-**Warning:** When Django starts up, some python scripts get loaded twice, which can cause 'already registered' errors to be thrown. If you place your calls to ``revisions.register()`` in the ``models.py`` file, immediately after the model definition, this problem will go away.
+**Warning:** When Django starts up, some python scripts get loaded twice, which can cause 'already registered' errors to be thrown. If you place your calls to ``reversion.register()`` in the ``models.py`` file, immediately after the model definition, this problem will go away.
 
 
 Creating revisions
@@ -58,27 +54,27 @@ A revision represents one or more changes made to your models, grouped together
 There are several ways to create revisions, as explained below. Although there is nothing stopping you from mixing and matching these approaches, it is recommended that you pick one of the methods and stick with it throughout your project.
 
 
-revisions.create_revision() decorator
+reversion.create_revision() decorator
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-You can decorate any function with the ``revisions.create_revision()`` decorator. Any changes to your models that occur during this function will be grouped together into a revision.
+You can decorate any function with the ``reversion.create_revision()`` decorator. Any changes to your models that occur during this function will be grouped together into a revision.
 
 ::
 
     @transaction.atomic()
-    @revisions.create_revision()
+    @reversion.create_revision()
     def you_view_func(request):
         your_model.save()
 
 
-revisions.create_revision() context manager
+reversion.create_revision() context manager
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 You can use a context manager to mark up a block of code. Once the block terminates, any changes made to your models will be grouped together into a revision.
 
 ::
 
-    with transaction.atomic(), revisions.create_revision():
+    with transaction.atomic(), reversion.create_revision():
         your_model.save()
 
 
@@ -94,7 +90,7 @@ To enable the revision middleware, simply add it to your ``MIDDLEWARE_CLASSES``
         # Other middleware goes here...
     )
 
-**Warning**: Due to changes in the Django 1.6 transaction handling, revision data will be saved in a separate database transaction to the one used to save your models, even if you set ``ATOMIC_REQUESTS = True``. If you need to ensure that your models and revisions are saved in the save transaction, please use the ``revisions.create_revision()`` context manager or decorator in combination with ``transaction.atomic()``.
+**Warning**: Due to changes in the Django 1.6 transaction handling, revision data will be saved in a separate database transaction to the one used to save your models, even if you set ``ATOMIC_REQUESTS = True``. If you need to ensure that your models and revisions are saved in the save transaction, please use the ``reversion.create_revision()`` context manager or decorator in combination with ``transaction.atomic()``.
 
 
 Version meta data
@@ -102,10 +98,10 @@ Version meta data
 
 It is possible to attach a comment and a user reference to an active revision using the following method::
 
-    with transaction.atomic(), revisions.create_revision():
+    with transaction.atomic(), reversion.create_revision():
         your_model.save()
-        revisions.set_user(user)
-        revisions.set_comment("Comment text...")
+        reversion.set_user(user)
+        reversion.set_comment("Comment text...")
 
 If you use ``RevisionMiddleware``, then the user will automatically be added to the revision from the incoming request.
 
@@ -123,7 +119,7 @@ You can attach custom meta data to a revision by creating a separate django mode
 
 You can then attach this meta class to a revision using the following method::
 
-    revisions.add_meta(VersionRating, rating=5)
+    reversion.add_meta(VersionRating, rating=5)
 
 
 Reverting to previous revisions
@@ -134,13 +130,13 @@ To revert a model to a previous version, use the following method::
     your_model = YourModel.objects.get(pk=1)
 
     # Build a list of all previous versions, latest versions first:
-    version_list = revisions.get_for_object(your_model)
+    version_list = reversion.get_for_object(your_model)
 
     # Build a list of all previous versions, latest versions first, duplicates removed:
-    version_list = revisions.get_for_object(your_model).get_unique()
+    version_list = reversion.get_for_object(your_model).get_unique()
 
     # Find the most recent version for a given date:
-    version = revisions.get_for_date(your_model, datetime.datetime(2008, 7, 10))
+    version = reversion.get_for_date(your_model, datetime.datetime(2008, 7, 10))
 
     # Access the model data stored within the version:
     version_data = version.field_dict
@@ -161,7 +157,7 @@ Recovering Deleted Objects
 To recover a deleted object, use the following method::
 
     # Built a list of all deleted objects, latest deletions first.
-    deleted_list = revisions.get_deleted(YourModel)
+    deleted_list = reversion.get_deleted(YourModel)
 
     # Access a specific deleted object.
     delete_version = deleted_list.get(id=5)
@@ -179,11 +175,11 @@ Advanced model registration
 Following foreign key relationships
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-Normally, when you save a model it will only save the primary key of any ForeignKey or ManyToMany fields. If you also wish to include the data of the foreign key in your revisions, pass a list of relationship names to the ``revisions.register()`` method.
+Normally, when you save a model it will only save the primary key of any ForeignKey or ManyToMany fields. If you also wish to include the data of the foreign key in your revisions, pass a list of relationship names to the ``reversion.register()`` method.
 
 ::
 
-    revisions.register(YourModel, follow=["your_foreign_key_field"])
+    reversion.register(YourModel, follow=["your_foreign_key_field"])
 
 **Please note:** If you use the follow parameter, you must also ensure that the related model has been registered with django-reversion.
 
@@ -195,8 +191,8 @@ In addition to ForeignKey and ManyToMany relationships, you can also specify rel
     class Pet(models.Model):
         person = models.ForeignKey(Person)
 
-    revisions.register(Person, follow=["pet_set"])
-    revisions.register(Pet)
+    reversion.register(Person, follow=["pet_set"])
+    reversion.register(Pet)
 
 Now whenever you save a revision containing a ``Person``, all related ``Pet`` instances will be automatically saved to the same revision.
 
@@ -213,19 +209,19 @@ For example::
     class Restaurant(Place):
         pass
 
-    revisions.register(Place)
-    revisions.register(Restaurant, follow=["place_ptr"])
+    reversion.register(Place)
+    reversion.register(Restaurant, follow=["place_ptr"])
 
 
 Saving a subset of fields
 ^^^^^^^^^^^^^^^^^^^^^^^^^
 
-If you only want a subset of fields to be saved to a revision, you can specify a ``fields`` or ``exclude`` argument to the ``revisions.register()`` method.
+If you only want a subset of fields to be saved to a revision, you can specify a ``fields`` or ``exclude`` argument to the ``reversion.register()`` method.
 
 ::
 
-    revisions.register(YourModel, fields=["pk", "foo", "bar"])
-    revisions.register(YourModel, exclude=["foo"])
+    reversion.register(YourModel, fields=["pk", "foo", "bar"])
+    reversion.register(YourModel, exclude=["foo"])
 
 **Please note:** If you are not careful, then it is possible to specify a combination of fields that will make the model impossible to recover. As such, approach this option with caution.
 
@@ -237,7 +233,7 @@ By default, django-reversion will serialize model data using the ``'json'`` seri
 
 ::
 
-    revisions.register(YourModel, format="yaml")
+    reversion.register(YourModel, format="yaml")
 
 **Please note:** The named serializer must serialize model data to a utf-8 encoded character string. Please verify that your serializer is compatible before using it with django-reversion.
 
@@ -252,15 +248,15 @@ By default, django-reversion saves a new revision whenever a model is saved, usi
     from django.db.models.signals import post_save
     from your_app.signals import custom_signal
 
-    revisions.register(YourModel, signals=[post_save, custom_signal])
+    reversion.register(YourModel, signals=[post_save, custom_signal])
 
-By default, revision data is serialized at the end of the ``revisions.create_revision()`` block, allowing foreign key references to be updated in the same block before the revision data is prepared. However, in some cases you might want to serialize the revision data immediately, such as times when the model is shortly going to be deleted.
+By default, revision data is serialized at the end of the ``reversion.create_revision()`` block, allowing foreign key references to be updated in the same block before the revision data is prepared. However, in some cases you might want to serialize the revision data immediately, such as times when the model is shortly going to be deleted.
 
 ::
 
     from django.db.models.signals import post_save, pre_delete
 
-    revisions.register(YourModel, signals=[post_save], eager_signals=[pre_delete])
+    reversion.register(YourModel, signals=[post_save], eager_signals=[pre_delete])
 
 **Important:** Creating revisions using the `pre_delete` signal is not recommended, as it alters the semantics of revision recovery. Only do this if you have a good understanding of the django-reversion internals.
 
@@ -268,14 +264,14 @@ By default, revision data is serialized at the end of the ``revisions.create_rev
 Really advanced registration
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-It's possible to customize almost every aspect of model registration by registering your model with a subclass of ``revisions.VersionAdapter``. Behind the scenes, ``revisions.register()`` does this anyway, but you can explicitly provide your own VersionAdapter if you need to perform really advanced customization.
+It's possible to customize almost every aspect of model registration by registering your model with a subclass of ``VersionAdapter``. Behind the scenes, ``reversion.register()`` does this anyway, but you can explicitly provide your own VersionAdapter if you need to perform really advanced customization.
 
 ::
 
-    class MyVersionAdapter(revisions.VersionAdapter):
+    class MyVersionAdapter(reversion.VersionAdapter):
         pass  # Please see the reversion source code for available methods to override.
 
-    revisions.register(MyModel, adapter_cls=MyVersionAdapter)
+    reversion.register(MyModel, adapter_cls=MyVersionAdapter)
 
 
 Automatic Registration by the Admin Interface
@@ -308,8 +304,8 @@ For example::
 
 Since ``Restaurant`` has been registered with a subclass of ``VersionAdmin``, the following registration calls will be made automatically::
 
-    revisions.register(Place)
-    revisions.register(Restaurant, follow=("place_ptr", "meal_set"))
-    revisions.register(Meal)
+    reversion.register(Place)
+    reversion.register(Restaurant, follow=("place_ptr", "meal_set"))
+    reversion.register(Meal)
 
 It is only necessary to manually register these models if you wish to override the default registration parameters. In most cases, however, the defaults will suit just fine.
diff --git a/docs/conf.py b/docs/conf.py
index 45d3047..998c66b 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -51,7 +51,7 @@ copyright = '2013, Dave Hall'
 # The short X.Y version.
 version = '1.10'
 # The full version, including alpha/beta/rc tags.
-release = '1.10.0'
+release = '1.10.2'
 
 # The language for content autogenerated by Sphinx. Refer to documentation
 # for a list of supported languages.
diff --git a/docs/diffs.rst b/docs/diffs.rst
index 688ae63..d9270e3 100644
--- a/docs/diffs.rst
+++ b/docs/diffs.rst
@@ -16,13 +16,14 @@ First of all, you need to use the :ref:`low level API <api>` to retrieve the ver
 
 ::
 
+    from reversion import revisions as reversion
     from reversion.helpers import generate_patch
 
     # Get the page object to generate diffs for.
     page = Page.objects.all()[0]
 
     # Get the two versions to compare.
-    available_versions = revisions.get_for_object(page)
+    available_versions = reversion.get_for_object(page)
 
     new_version = available_versions[0]
     old_version = available_versions[1]
diff --git a/docs/django-versions.rst b/docs/django-versions.rst
index 9eeebad..027ec76 100644
--- a/docs/django-versions.rst
+++ b/docs/django-versions.rst
@@ -10,9 +10,9 @@ If you are using anything other than the latest release of Django, it is importa
 ==============  =================
 Django version  Reversion release
 ==============  =================
-1.7+            1.10.0
+1.7+            1.10.2
 1.6+            1.8.5
-1.5.1+          1.7.1
+1.5.1+          1.7.2
 1.5             1.7
 1.4.4+          1.6.6
 1.4.3           1.6.5
diff --git a/docs/how-it-works.rst b/docs/how-it-works.rst
index f6da095..7fdbba8 100644
--- a/docs/how-it-works.rst
+++ b/docs/how-it-works.rst
@@ -6,19 +6,19 @@ How it works
 Saving Revisions
 ----------------
 
-Enabling version control for a model is achieved using the ``revisions.register`` method. This registers the version control machinery with the ``post_save`` signal for that model, allowing new changes to the model to be caught.
+Enabling version control for a model is achieved using the ``reversion.register`` method. This registers the version control machinery with the ``post_save`` signal for that model, allowing new changes to the model to be caught.
 
 ::
 
-    from reversion import revisions
+    from reversion import revisions as reversion
 
-    revisions.register(YourModel)
+    reversion.register(YourModel)
 
 Any models that use subclasses of ``VersionAdmin`` in the admin interface will be automatically registered with django-reversion. As such, it is only necessary to manually register these models if you wish to override the default registration settings.
 
 Whenever you save changes to a model, it is serialized using the Django serialization framework into a JSON string. This is saved to the database as a ``reversion.models.Version`` model. Each ``Version`` model is linked to a model instance using a ``GenericForeignKey``.
 
-Foreign keys and many-to-many relationships are normally saved as their primary keys only. However, the ``revisions.register`` method takes an optional follow clause allowing these relationships to be automatically added to revisions. Please see :ref:`Low Level API <api>` for more information.
+Foreign keys and many-to-many relationships are normally saved as their primary keys only. However, the ``reversion.register`` method takes an optional follow clause allowing these relationships to be automatically added to revisions. Please see :ref:`Low Level API <api>` for more information.
 
 Reverting Versions
 ------------------
diff --git a/setup.py b/setup.py
index e285854..06fd5a5 100644
--- a/setup.py
+++ b/setup.py
@@ -31,7 +31,7 @@ setup(
         "reversion": ["locale/*/LC_MESSAGES/django.*", "templates/reversion/*.html"]},
     cmdclass = cmdclass,
     install_requires = [
-        "django>=1.7",
+        "django>=1.8",
     ],
     extras_require = {
         "diff": [
@@ -48,7 +48,6 @@ setup(
         "License :: OSI Approved :: BSD License",
         "Operating System :: OS Independent",
         "Programming Language :: Python",
-        'Programming Language :: Python :: 2.6',
         'Programming Language :: Python :: 2.7',
         'Programming Language :: Python :: 3.2',
         'Programming Language :: Python :: 3.3',
diff --git a/src/reversion/__init__.py b/src/reversion/__init__.py
index c0af08d..2a83594 100644
--- a/src/reversion/__init__.py
+++ b/src/reversion/__init__.py
@@ -9,4 +9,4 @@ Developed by Dave Hall.
 from __future__ import unicode_literals
 
 
-__version__ = VERSION = (1, 10, 0)
+__version__ = VERSION = (1, 10, 2)
diff --git a/src/reversion/admin.py b/src/reversion/admin.py
index 2461e24..4e97591 100644
--- a/src/reversion/admin.py
+++ b/src/reversion/admin.py
@@ -8,10 +8,7 @@ from django.db import models, transaction, connection
 from django.conf.urls import url
 from django.contrib import admin
 from django.contrib.admin import options
-try:
-    from django.contrib.admin.utils import unquote, quote
-except ImportError:  # Django < 1.7  pragma: no cover
-    from django.contrib.admin.util import unquote, quote
+from django.contrib.admin.utils import unquote, quote
 try:
     from django.contrib.contenttypes.admin import GenericInlineModelAdmin
     from django.contrib.contenttypes.fields import GenericRelation
@@ -92,14 +89,16 @@ class VersionAdmin(admin.ModelAdmin):
 
     def log_addition(self, request, object, change_message=None):
         change_message = change_message or _("Initial version.")
-        self.revision_context_manager.set_comment(change_message)
+        if self.revision_context_manager.is_active():
+            self.revision_context_manager.set_comment(change_message)
         try:
             super(VersionAdmin, self).log_addition(request, object, change_message)
         except TypeError:  # Django < 1.9 pragma: no cover
             super(VersionAdmin, self).log_addition(request, object)
 
     def log_change(self, request, object, message):
-        self.revision_context_manager.set_comment(message)
+        if self.revision_context_manager.is_active():
+            self.revision_context_manager.set_comment(message)
         super(VersionAdmin, self).log_change(request, object, message)
 
     # Auto-registration.
@@ -136,7 +135,13 @@ class VersionAdmin(admin.ModelAdmin):
                         fk_name = field.name
                         break
             if fk_name and not inline_model._meta.get_field(fk_name).rel.is_hidden():
-                accessor = inline_model._meta.get_field(fk_name).related.get_accessor_name()
+                field = inline_model._meta.get_field(fk_name)
+                try:
+                    # >=django1.9
+                    remote_field = field.remote_field
+                except AttributeError:
+                    remote_field = field.related
+                accessor = remote_field.get_accessor_name()
                 follow_field = accessor
         return inline_model, follow_field, fk_name
 
@@ -206,17 +211,21 @@ class VersionAdmin(admin.ModelAdmin):
             raise PermissionDenied
         # Render the recover view.
         version = get_object_or_404(Version, pk=version_id)
-        return self.revisionform_view(request, version, self.recover_form_template or self._get_template_list("recover_form.html"), {
+        context = {
             "title": _("Recover %(name)s") % {"name": version.object_repr},
-        })
+        }
+        context.update(extra_context or {})
+        return self.revisionform_view(request, version, self.recover_form_template or self._get_template_list("recover_form.html"), context)
 
     def revision_view(self, request, object_id, version_id, extra_context=None):
         """Displays the contents of the given revision."""
         object_id = unquote(object_id) # Underscores in primary key get quoted to "_5F"
         version = get_object_or_404(Version, pk=version_id, object_id=object_id)
-        return self.revisionform_view(request, version, self.revision_form_template or self._get_template_list("revision_form.html"), {
+        context = {
             "title": _("Revert %(name)s") % {"name": version.object_repr},
-        })
+        }
+        context.update(extra_context or {})
+        return self.revisionform_view(request, version, self.revision_form_template or self._get_template_list("revision_form.html"), context)
 
     def changelist_view(self, request, extra_context=None):
         """Renders the change view."""
diff --git a/src/reversion/management/commands/createinitialrevisions.py b/src/reversion/management/commands/createinitialrevisions.py
index bf76acd..d524670 100644
--- a/src/reversion/management/commands/createinitialrevisions.py
+++ b/src/reversion/management/commands/createinitialrevisions.py
@@ -1,62 +1,41 @@
 from __future__ import unicode_literals
 
-from optparse import make_option
-try:
-    from collections import OrderedDict
-except ImportError:  # For Python 2.6
-    from django.utils.datastructures import SortedDict as OrderedDict
-
-try:
-    from django.apps import apps
-    try:
-        get_app = apps.get_app
-    except AttributeError:  # For Django >= 1.9
-        get_app = lambda app_label: apps.get_app_config(app_label).models_module
-    try:
-        get_apps = apps.get_apps
-    except AttributeError:  # For Django >= 1.9
-        get_apps = lambda: [app_config.models_module for app_config in apps.get_app_configs() if app_config.models_module is not None]
-    get_model = apps.get_model
-    get_models = apps.get_models
-except ImportError:  # For Django < 1.7
-    from django.db.models import get_app, get_apps, get_model, get_models
-
-try:
-    from importlib import import_module
-except ImportError:  # For Django < 1.8
-    from django.utils.importlib import import_module
+from collections import OrderedDict
+from importlib import import_module
 
+from django.apps import apps
+from django.conf import settings
 from django.core.exceptions import ImproperlyConfigured
 from django.core.management.base import BaseCommand
 from django.core.management.base import CommandError
 from django.contrib.contenttypes.models import ContentType
 from django.db import reset_queries
+from django.utils import translation
 from django.utils.encoding import force_text
 
 from reversion.revisions import default_revision_manager
 from reversion.models import Version, has_int_pk
-from django.utils import translation
-from django.conf import settings
+
+get_app = lambda app_label: apps.get_app_config(app_label).models_module
 
 
 class Command(BaseCommand):
-    option_list = BaseCommand.option_list + (
-        make_option("--comment",
+    help = "Creates initial revisions for a given app [and model]."
+
+    def add_arguments(self, parser):
+        parser.add_argument('args', metavar='app_label', nargs='*',
+            help="Optional apps or app.Model list.")
+        parser.add_argument("--comment",
             action="store",
-            dest="comment",
             default="Initial version.",
-            help='Specify the comment to add to the revisions. Defaults to "Initial version.".'),
-        make_option("--batch-size",
+            help='Specify the comment to add to the revisions. Defaults to "Initial version.".')
+        parser.add_argument("--batch-size",
             action="store",
-            dest="batch_size",
             type=int,
             default=500,
-            help="For large sets of data, revisions will be populated in batches. Defaults to 500"),
-        make_option('--database', action='store', dest='database',
-            help='Nominates a database to create revisions in.'),
-        )
-    args = '[appname, appname.ModelName, ...] [--comment="Initial version."]'
-    help = "Creates initial revisions for a given app [and model]."
+            help="For large sets of data, revisions will be populated in batches. Defaults to 500.")
+        parser.add_argument("--database",
+            help='Nominates a database to create revisions in.')
 
     def handle(self, *app_labels, **options):
 
@@ -71,10 +50,12 @@ class Command(BaseCommand):
         app_list = OrderedDict()
         # if no apps given, use all installed.
         if len(app_labels) == 0:
-            for app in get_apps():
+            all_apps = [config.models_module for config in apps.get_app_configs()
+                        if config.models_module is not None]
+            for app in all_apps:
                 if not app in app_list:
                     app_list[app] = []
-                for model_class in get_models(app):
+                for model_class in apps.get_models(app):
                     if not model_class in app_list[app]:
                         app_list[app].append(model_class)
         else:
@@ -86,7 +67,7 @@ class Command(BaseCommand):
                     except ImproperlyConfigured:
                         raise CommandError("Unknown application: %s" % app_label)
 
-                    model_class = get_model(app_label, model_label)
+                    model_class = apps.get_model(app_label, model_label)
                     if model_class is None:
                         raise CommandError("Unknown model: %s.%s" % (app_label, model_label))
                     if app in app_list:
@@ -101,7 +82,7 @@ class Command(BaseCommand):
                         app = get_app(app_label)
                         if not app in app_list:
                             app_list[app] = []
-                        for model_class in get_models(app):
+                        for model_class in apps.get_models(app):
                             if not model_class in app_list[app]:
                                 app_list[app].append(model_class)
                     except ImproperlyConfigured:
diff --git a/src/reversion/management/commands/deleterevisions.py b/src/reversion/management/commands/deleterevisions.py
index e5693c2..c58cf2e 100644
--- a/src/reversion/management/commands/deleterevisions.py
+++ b/src/reversion/management/commands/deleterevisions.py
@@ -1,7 +1,7 @@
 from __future__ import unicode_literals
 
 import datetime, operator
-from optparse import make_option
+from functools import reduce
 
 from django.core.management.base import BaseCommand
 from django.core.management.base import CommandError
@@ -14,36 +14,6 @@ from django.db.utils import DatabaseError
 
 
 class Command(BaseCommand):
-    option_list = BaseCommand.option_list + (
-        make_option("--date", "-t",
-            dest="date",
-            help="Delete only revisions older than the specify date. The date should be a valid date given in the ISO format (YYYY-MM-DD)"),
-        make_option("--days", "-d",
-            dest="days",
-            default=0,
-            type="int",
-            help="Delete only revisions older than the specify number of days."),
-        make_option("--keep-revision", "-k",
-            dest="keep",
-            default=0,
-            type="int",
-            help="Keep the specified number of revisions (most recent) for each object."),
-        make_option("--force", "-f",
-            action="store_true",
-            dest="force",
-            default=False,
-            help="Force the deletion of revisions even if an other app/model is involved"),
-        make_option("--no-confirmation", "-c",
-            action="store_false",
-            dest="confirmation",
-            default=True,
-            help="Disable the confirmation before deleting revisions"),
-        make_option('--manager', '-m', dest='manager',
-            help='Delete revisions only from specified manager. Defaults from all managers.'),
-        make_option('--database', action='store', dest='database',
-            help='Nominates a database to delete revisions from.'),
-        )
-    args = "[appname, appname.ModelName, ...] [--date=YYYY-MM-DD | days=0] [--keep=0] [--force] [--no-confirmation]"
     help = """Deletes revisions for a given app [and model] and/or before a specified delay or date.
     
 If an app or a model is specified, revisions that have an other app/model involved will not be deleted. Use --force to avoid that.
@@ -69,6 +39,34 @@ Examples:
     That will delete only revisions of myapp.model if there's more than 10 revisions for an object, keeping the 10 most recent revisons.
 """
 
+    def add_arguments(self, parser):
+        parser.add_argument('args', metavar='app_label', nargs='*',
+            help="Optional apps or app.Model list.")
+        parser.add_argument("-t", "--date",
+            help="Delete only revisions older than the specify date. The date should be a valid date given in the ISO format (YYYY-MM-DD)")
+        parser.add_argument("-d", "--days",
+            default=0,
+            type=int,
+            help="Delete only revisions older than the specify number of days.")
+        parser.add_argument("-k", "--keep-revision",
+            dest="keep",
+            default=0,
+            type=int,
+            help="Keep the specified number of revisions (most recent) for each object.")
+        parser.add_argument("-f", "--force",
+            action="store_true",
+            default=False,
+            help="Force the deletion of revisions even if an other app/model is involved")
+        parser.add_argument("-c", "--no-confirmation",
+            action="store_false",
+            dest="confirmation",
+            default=True,
+            help="Disable the confirmation before deleting revisions")
+        parser.add_argument("-m", "--manager",
+            help="Delete revisions only from specified manager. Defaults from all managers.")
+        parser.add_argument("--database",
+            help='Nominates a database to delete revisions from.')
+
     def handle(self, *app_labels, **options):
         days = options["days"]
         keep = options["keep"]
@@ -203,7 +201,8 @@ Examples:
 
 
         # Delete versions and revisions
-        print("Deleting revisions...")
+        if verbosity > 0:
+            print("Deleting revisions...")
         
         try:
             revision_query.delete()
@@ -213,4 +212,5 @@ Examples:
             for item in revision_query:
                 item.delete()
                 
-        print("Done")
+        if verbosity > 0:
+            return "Done"
diff --git a/src/reversion/models.py b/src/reversion/models.py
index f1b8177..ea55c5a 100644
--- a/src/reversion/models.py
+++ b/src/reversion/models.py
@@ -134,6 +134,7 @@ class Version(models.Model):
     objects = VersionQuerySet.as_manager()
 
     revision = models.ForeignKey(Revision,
+                                 on_delete=models.CASCADE,
                                  help_text="The revision that contains this version.")
 
     object_id = models.TextField(help_text="Primary key of the model under version control.")
@@ -146,6 +147,7 @@ class Version(models.Model):
     )
 
     content_type = models.ForeignKey(ContentType,
+                                     on_delete=models.CASCADE,
                                      help_text="Content type of the model under version control.")
 
     # A link to the current instance, not the version stored in this Version!
diff --git a/src/reversion/revisions.py b/src/reversion/revisions.py
index 25df3e8..fd2c052 100644
--- a/src/reversion/revisions.py
+++ b/src/reversion/revisions.py
@@ -9,12 +9,7 @@ from weakref import WeakValueDictionary
 import copy
 from collections import defaultdict
 
-try:
-    from django.apps import apps
-    get_model = apps.get_model
-except ImportError:  # For Django < 1.7  pragma: no cover
-    from django.db.models import get_model
-
+from django.apps import apps
 from django.contrib.contenttypes.models import ContentType
 from django.core import serializers
 from django.core.exceptions import ObjectDoesNotExist
@@ -25,7 +20,6 @@ from django.db.models.query import QuerySet
 from django.db.models.signals import post_save
 from django.utils.encoding import force_text
 
-from reversion.models import Revision, Version, has_int_pk
 from reversion.signals import pre_revision_commit, post_revision_commit
 from reversion.errors import RevisionManagementError, RegistrationError
 
@@ -103,6 +97,7 @@ class VersionAdapter(object):
 
     def get_version_data(self, obj, db=None):
         """Creates the version data to be saved to the version model."""
+        from reversion.models import has_int_pk
         object_id = force_text(obj.pk)
         content_type = ContentType.objects.db_manager(db).get_for_model(obj)
         if has_int_pk(obj.__class__):
@@ -378,7 +373,7 @@ class RevisionManager(object):
     def get_registered_models(self):
         """Returns an iterable of all registered models."""
         return [
-            get_model(*key)
+            apps.get_model(*key)
             for key
             in self._registered_models.keys()
         ]
@@ -452,12 +447,14 @@ class RevisionManager(object):
 
     def _get_versions(self, db=None):
         """Returns all versions that apply to this manager."""
+        from reversion.models import Version
         return Version.objects.using(db).filter(
             revision__manager_slug = self._manager_slug,
         ).select_related("revision")
 
     def save_revision(self, objects, ignore_duplicates=False, user=None, comment="", meta=(), db=None):
         """Saves a new revision."""
+        from reversion.models import Revision, Version, has_int_pk
         # Adapt the objects to a dict.
         if isinstance(objects, (list, tuple)):
             objects = dict(
@@ -468,7 +465,7 @@ class RevisionManager(object):
         if objects:
             # Follow relationships.
             for obj in self._follow_relationships(objects.keys()):
-                if not obj in objects:
+                if obj not in objects:
                     adapter = self.get_adapter(obj.__class__)
                     objects[obj] = adapter.get_version_data(obj)
             # Create all the versions without saving them
@@ -529,6 +526,7 @@ class RevisionManager(object):
 
         The results are returned with the most recent versions first.
         """
+        from reversion.models import has_int_pk
         content_type = ContentType.objects.db_manager(db).get_for_model(model)
         versions = self._get_versions(db).filter(
             content_type = content_type,
@@ -565,6 +563,7 @@ class RevisionManager(object):
 
     def get_for_date(self, object, date, db=None):
         """Returns the latest version of an object for the given date."""
+        from reversion.models import Version
         versions = self.get_for_object(object, db)
         versions = versions.filter(revision__date_created__lte=date)
         try:
@@ -580,6 +579,7 @@ class RevisionManager(object):
 
         The results are returned with the most recent versions first.
         """
+        from reversion.models import has_int_pk
         model_db = model_db or db
         content_type = ContentType.objects.db_manager(db).get_for_model(model_class)
         live_pk_queryset = model_class._default_manager.db_manager(model_db).all().values_list("pk", flat=True)
diff --git a/src/reversion/south_migrations/0001_initial.py b/src/reversion/south_migrations/0001_initial.py
deleted file mode 100644
index 5df1272..0000000
--- a/src/reversion/south_migrations/0001_initial.py
+++ /dev/null
@@ -1,104 +0,0 @@
-# encoding: utf-8
-import datetime
-from south.db import db
-from south.v2 import SchemaMigration
-from django.db import models
-
-try:
-    from django.contrib.auth import get_user_model
-except ImportError: # django < 1.5
-    from django.contrib.auth.models import User
-else:
-    User = get_user_model()
-
-
-class Migration(SchemaMigration):
-
-    def forwards(self, orm):
-        
-        # Adding model 'Revision'
-        db.create_table('reversion_revision', (
-            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
-            ('date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
-            ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm["%s.%s" % (User._meta.app_label, User._meta.object_name)], null=True, blank=True)),
-            ('comment', self.gf('django.db.models.fields.TextField')(blank=True)),
-        ))
-        db.send_create_signal('reversion', ['Revision'])
-
-        # Adding model 'Version'
-        db.create_table('reversion_version', (
-            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
-            ('revision', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['reversion.Revision'])),
-            ('object_id', self.gf('django.db.models.fields.TextField')()),
-            ('content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'])),
-            ('format', self.gf('django.db.models.fields.CharField')(max_length=255)),
-            ('serialized_data', self.gf('django.db.models.fields.TextField')()),
-            ('object_repr', self.gf('django.db.models.fields.TextField')()),
-        ))
-        db.send_create_signal('reversion', ['Version'])
-
-    def backwards(self, orm):
-        
-        # Deleting model 'Revision'
-        db.delete_table('reversion_revision')
-
-        # Deleting model 'Version'
-        db.delete_table('reversion_version')
-
-    models = {
-        'auth.group': {
-            'Meta': {'object_name': 'Group'},
-            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
-            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
-            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
-        },
-        'auth.permission': {
-            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
-            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
-            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
-            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
-            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
-        },
-        "%s.%s" % (User._meta.app_label, User._meta.module_name): {
-            'Meta': {'object_name': User.__name__, "db_table": "'%s'" % User._meta.db_table},
-            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
-            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
-            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
-            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
-            User._meta.pk.column: ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
-            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
-            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
-            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
-            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
-            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
-            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
-            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
-            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
-        },
-        'contenttypes.contenttype': {
-            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
-            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
... 945 lines suppressed ...

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/django-reversion.git



More information about the Python-modules-commits mailing list