diff --git a/README.md b/README.md index 1f5e775..211aa7c 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # Django Admin Sortable -[![Build Status](https://travis-ci.org/iambrandontaylor/django-admin-sortable.svg?branch=master)](https://travis-ci.org/iambrandontaylor/django-admin-sortable) - -Current version: 2.0.21 +[![PyPI version](https://img.shields.io/pypi/v/django-admin-sortable.svg)](https://pypi.python.org/pypi/django-admin-sortable) +[![Python versions](https://img.shields.io/pypi/pyversions/django-admin-sortable.svg)](https://pypi.python.org/pypi/django-admin-sortable) +[![Build Status](https://travis-ci.org/alsoicode/django-admin-sortable.svg?branch=master)](https://travis-ci.org/alsoicode/django-admin-sortable) This project makes it easy to add drag-and-drop ordering to any model in Django admin. Inlines for a sortable model may also be made sortable, @@ -17,9 +17,9 @@ Sorting inlines: ![sortable-inlines](http://res.cloudinary.com/alsoicode/image/upload/v1451237555/django-admin-sortable/sortable-inlines.jpg) ## Supported Django Versions -For Django 1.5.x to 1.9.x, use version 2.0.18. +For Django 1.5.x to 1.7.x, use version 2.0.18. -For Django 1.10.x, use 2.0.19 or higher. +For Django 1.8.x or higher, use the latest version. ### Other notes of interest regarding versions django-admin-sortable 1.5.2 introduced backward-incompatible changes for Django 1.4.x @@ -43,7 +43,8 @@ Download django-admin-sortable from [source](https://github.com/iambrandontaylor ## Configuration 1. Add `adminsortable` to your `INSTALLED_APPS`. -2. Ensure `django.core.context_processors.static` is in your `TEMPLATE_CONTEXT_PROCESSORS`. +2. Ensure `django.template.context_processors.static` is in your `TEMPLATES["OPTIONS"]["context_processors"]`. + - (In older versions of Django, ensure `django.core.context_processors.static` is in `TEMPLATE_CONTEXT_PROCESSORS` instead.) 3. Ensure that `CSRF_COOKIE_HTTPONLY` has not been set to `True`, as django-admin-sortable is currently incompatible with that setting. @@ -81,6 +82,7 @@ To add "sortability" to a model, you need to inherit `SortableMixin` and at mini - `BigIntegerField` - `Meta.ordering` **must only contain one value**, otherwise, your objects will not be sorted correctly. +- **IMPORTANT**: You must name the field you use for ordering something other than "order_field" as this name is reserved by the `SortableMixin` class. - It is recommended that you set `editable=False` and `db_index=True` on the field defined in `Meta.ordering` for a seamless Django admin experience and faster lookups on the objects. Sample Model: @@ -197,17 +199,17 @@ If you previously used Django Admin Sortable, **DON'T PANIC** - everything will Please note however that the `Sortable` class still contains the hard-coded `order` field, and meta inheritance requirements: ```python - # legacy model definition +# legacy model definition - from adminsortable.models import Sortable +from adminsortable.models import Sortable - class Project(Sortable): - class Meta(Sortable.Meta): - pass - title = models.CharField(max_length=50) +class Project(Sortable): + class Meta(Sortable.Meta): + pass + title = models.CharField(max_length=50) - def __unicode__(self): - return self.title + def __unicode__(self): + return self.title ``` #### Model Instance Methods @@ -407,16 +409,16 @@ change_list_template_extends These attributes have default values of: ```python - change_form_template_extends = 'admin/change_form.html' - change_list_template_extends = 'admin/change_list.html' +change_form_template_extends = 'admin/change_form.html' +change_list_template_extends = 'admin/change_list.html' ``` -If you need to extend the inline change form templates, you'll need to select the right one, depending on your version of Django. For Django 1.5.x or below, you'll need to extend one of the following: +If you need to extend the inline change form templates, you'll need to select the right one, depending on your version of Django. For 1.10.x or below, you'll need to extend one of the following: - templates/adminsortable/edit_inline/stacked-1.5.x.html - templates/adminsortable/edit_inline/tabular-inline-1.5.x.html + templates/adminsortable/edit_inline/stacked-1.10.x.html + templates/adminsortable/edit_inline/tabular-inline-1.10.x.html -For Django 1.6.x, extend: +otherwise, extend: templates/adminsortable/edit_inline/stacked.html templates/adminsortable/edit_inline/tabular.html @@ -458,15 +460,16 @@ plugin_pool.register_plugin(CMSCarouselPlugin) The contents of `sortable-stacked-inline-change-form.html` at a minimum need to extend the extrahead block with: -```html +```html+django {% extends "admin/cms/page/plugin_change_form.html" %} {% load static from staticfiles %} {% block extrahead %} {{ block.super }} - - - + + + + {% endblock extrahead %} @@ -474,16 +477,44 @@ the extrahead block with: Sorting within Django-CMS is really only feasible for inline models of a plugin as Django-CMS already includes sorting for plugin instances. For tabular inlines, just substitute: -```html - +```html+django + ``` with: -```html - +```html+django + ``` +### Notes +From ``django-cms 3.x`` the path of change_form.html has changed. Replace the follwing line: + +```html+django +{% extends "admin/cms/page/plugin_change_form.html" %} +``` + +with + +```html+django +{% extends "admin/cms/page/plugin/change_form.html" %} +``` + +From ``django-admin-sortable 2.0.13`` the ``jquery.django-csrf.js`` was removed and you have to include the snippet-template. +Change the following line: + +```html+django + +``` + +to + +```html+django +{% include 'adminsortable/csrf/jquery.django-csrf.html' with csrf_cookie_name='csrftoken' %} +``` + +Please note, if you change the ``CSRF_COOKIE_NAME`` you have to adjust ``csrf_cookie_name='YOUR_CSRF_COOKIE_NAME'`` + ### Rationale Other projects have added drag-and-drop ordering to the ChangeList view, however this introduces a couple of problems... @@ -500,8 +531,8 @@ ordering on top of that just seemed a little much in my opinion. ### Status django-admin-sortable is currently used in production. -### What's new in 2.0.21? -- Fixed a regression introduced by [ Pull Request 143](https://github.com/iambrandontaylor/django-admin-sortable/pull/143) which caused models sortable by a foriegn key to not persist the sort order correctly. +### What's new in 2.1.4? +- Improved performance on large data sets. Credit to [mrmachine](https://github.com/mrmachine). ### Future - Better template support for foreign keys that are self referential. If someone would like to take on rendering recursive sortables, that would be super. diff --git a/README.rst b/README.rst index 87ff9ee..e71e708 100644 --- a/README.rst +++ b/README.rst @@ -1,9 +1,7 @@ Django Admin Sortable ===================== -|Build Status| - -Current version: 2.0.21 +|PyPI version| |Python versions| |Build Status| This project makes it easy to add drag-and-drop ordering to any model in Django admin. Inlines for a sortable model may also be made sortable, @@ -26,9 +24,9 @@ Sorting inlines: Supported Django Versions ------------------------- -For Django 1.5.x to 1.9.x, use version 2.0.18. +For Django 1.5.x to 1.7.x, use version 2.0.18. -For Django 1.10.x, use 2.0.19 or higher. +For Django 1.8.x or higher, use the latest version. Other notes of interest regarding versions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -38,7 +36,7 @@ Django 1.4.x django-admin-sortable 1.6.6 introduced a backward-incompatible change for the ``sorting_filters`` attribute. Please convert your attributes to -the new tuple-based format if you haven't already. +the new tuple-based format if you haven’t already. django-admin-sortable 1.7.1 and higher are compatible with Python 3. @@ -47,7 +45,7 @@ Installation 1. ``$ pip install django-admin-sortable`` ---or-- +–or– Download django-admin-sortable from `source `__ @@ -64,8 +62,13 @@ Configuration ------------- 1. Add ``adminsortable`` to your ``INSTALLED_APPS``. -2. Ensure ``django.core.context_processors.static`` is in your - ``TEMPLATE_CONTEXT_PROCESSORS``. +2. Ensure ``django.template.context_processors.static`` is in your + ``TEMPLATES["OPTIONS"]["context_processors"]``. + + - (In older versions of Django, ensure + ``django.core.context_processors.static`` is in + ``TEMPLATE_CONTEXT_PROCESSORS`` instead.) + 3. Ensure that ``CSRF_COOKIE_HTTPONLY`` has not been set to ``True``, as django-admin-sortable is currently incompatible with that setting. @@ -81,11 +84,11 @@ to the location you serve static files from. Testing ~~~~~~~ -Have a look at the included sample\_project to see working examples. The +Have a look at the included sample_project to see working examples. The login credentials for admin are: admin/admin When a model is sortable, a tool-area link will be added that says -"Change Order". Click this link, and you will be taken to the custom +“Change Order”. Click this link, and you will be taken to the custom view where you can drag-and-drop the records into order. Inlines may be drag-and-dropped into any order directly from the change @@ -97,11 +100,11 @@ Usage Models ~~~~~~ -To add "sortability" to a model, you need to inherit ``SortableMixin`` +To add “sortability” to a model, you need to inherit ``SortableMixin`` and at minimum, define: - The field which should be used for ``Meta.ordering``, which must - resolve to one of the integer fields defined in Django's ORM: + resolve to one of the integer fields defined in Django’s ORM: - ``PositiveIntegerField`` - ``IntegerField`` - ``PositiveSmallIntegerField`` @@ -110,6 +113,9 @@ and at minimum, define: - ``Meta.ordering`` **must only contain one value**, otherwise, your objects will not be sorted correctly. +- **IMPORTANT**: You must name the field you use for ordering something + other than “order_field” as this name is reserved by the + ``SortableMixin`` class. - It is recommended that you set ``editable=False`` and ``db_index=True`` on the field defined in ``Meta.ordering`` for a seamless Django admin experience and faster lookups on the objects. @@ -137,14 +143,14 @@ Sample Model: def __unicode__(self): return self.title -Support for models that don't use an ``AutoField`` for their primary key +Support for models that don’t use an ``AutoField`` for their primary key are also supported in version 2.0.20 or higher. Common Use Case ^^^^^^^^^^^^^^^ A common use case is to have child objects that are sortable relative to -a parent. If your parent object is also sortable, here's how you would +a parent. If your parent object is also sortable, here’s how you would set up your models and admin options: .. code:: python @@ -235,7 +241,7 @@ will be grouped by the non-sortable foreign key when sorting. Backwards Compatibility ~~~~~~~~~~~~~~~~~~~~~~~ -If you previously used Django Admin Sortable, **DON'T PANIC** - +If you previously used Django Admin Sortable, **DON’T PANIC** - everything will still work exactly as before ***without any changes to your code***. Going forward, it is recommended that you use the new ``SortableMixin`` on your models, as pre-2.0 compatibility might not be @@ -246,17 +252,17 @@ hard-coded ``order`` field, and meta inheritance requirements: .. code:: python - # legacy model definition + # legacy model definition - from adminsortable.models import Sortable + from adminsortable.models import Sortable - class Project(Sortable): - class Meta(Sortable.Meta): - pass - title = models.CharField(max_length=50) + class Project(Sortable): + class Meta(Sortable.Meta): + pass + title = models.CharField(max_length=50) - def __unicode__(self): - return self.title + def __unicode__(self): + return self.title Model Instance Methods ^^^^^^^^^^^^^^^^^^^^^^ @@ -283,7 +289,7 @@ following data: | | Child Model 4 | | | Child Model 5 | -"Child Model 2" ``get_next()`` would return ``None`` "Child Model 3" +“Child Model 2” ``get_next()`` would return ``None`` “Child Model 3” ``get_previous`` would return ``None`` If you wish to override this behavior, pass in: @@ -293,7 +299,7 @@ If you wish to override this behavior, pass in: your_instance.get_next(filter_on_sortable_fk=False) -You may also pass in additional ORM "extra\_filters" as a dictionary, +You may also pass in additional ORM “extra_filters” as a dictionary, should you need to: .. code:: python @@ -306,13 +312,13 @@ Adding Sorting to an existing model Django 1.5.x to 1.6.x ^^^^^^^^^^^^^^^^^^^^^ -If you're adding Sorting to an existing model, it is recommended that +If you’re adding Sorting to an existing model, it is recommended that you use `django-south `__ to create a schema -migration to add the "order" field to your model. You will also need to +migration to add the “order” field to your model. You will also need to create a data migration in order to add the appropriate values for the -"order" column. +“order” column. -Example assuming a model named "Category": +Example assuming a model named “Category”: .. code:: python @@ -328,7 +334,7 @@ more information on South Data Migrations. Django 1.7.x or higher ^^^^^^^^^^^^^^^^^^^^^^ -Since schema migrations are built into Django 1.7, you don't have to use +Since schema migrations are built into Django 1.7, you don’t have to use south, but the process of adding and running migrations is nearly identical. Take a look at the `Migrations `__ @@ -399,8 +405,8 @@ Overriding ``queryset()`` django-admin-sortable supports custom queryset overrides on admin models and inline models in Django admin! -If you're providing an override of a SortableAdmin or Sortable inline -model, you don't need to do anything extra. django-admin-sortable will +If you’re providing an override of a SortableAdmin or Sortable inline +model, you don’t need to do anything extra. django-admin-sortable will automatically honor your queryset. Have a look at the WidgetAdmin class in the sample project for an @@ -435,7 +441,7 @@ properly determine the sortability of your model. Example: return qs If you override the queryset of an inline, the number of objects present -may change, and adminsortable won't be able to automatically determine +may change, and adminsortable won’t be able to automatically determine if the inline model is sortable from here, which is why we have to set the ``is_sortable`` property of the model in this method. @@ -447,28 +453,28 @@ a ``sorting_filters`` tuple. This works exactly the same as ``.filter()`` on a QuerySet, and is applied *after* ``get_queryset()`` on the admin class, allowing you to override the queryset as you would normally in admin but apply additional filters for sorting. The text -"Change Order of" will appear before each filter in the Change List +“Change Order of” will appear before each filter in the Change List template, and the filter groups are displayed from left to right in the -order listed. If no ``sorting_filters`` are specified, the text "Change -Order" will be displayed for the link. +order listed. If no ``sorting_filters`` are specified, the text “Change +Order” will be displayed for the link. Self-Referential SortableForeignKey ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ You can specify a self-referential SortableForeignKey field, however the admin interface will currently show a model that is a grandchild at the -same level as a child. I'm working to resolve this issue. +same level as a child. I’m working to resolve this issue. Important! '''''''''' django-admin-sortable 1.6.6 introduced a backwards-incompatible change for ``sorting_filters``. Previously this attribute was defined as a -dictionary, so you'll need to change your values over to the new +dictionary, so you’ll need to change your values over to the new tuple-based format. -An example of sorting subsets would be a "Board of Directors". In this -use case, you have a list of "People" objects. Some of these people are +An example of sorting subsets would be a “Board of Directors”. In this +use case, you have a list of “People” objects. Some of these people are on the Board of Directors and some not, and you need to sort them independently. @@ -493,9 +499,9 @@ independently. Extending custom templates ^^^^^^^^^^^^^^^^^^^^^^^^^^ -By default, adminsortable's change form and change list views inherit -from Django admin's standard templates. Sometimes you need to have a -custom change form or change list, but also need adminsortable's CSS and +By default, adminsortable’s change form and change list views inherit +from Django admin’s standard templates. Sometimes you need to have a +custom change form or change list, but also need adminsortable’s CSS and JavaScript for inline models that are sortable for example. SortableAdmin has two attributes you can override for this use case: @@ -509,27 +515,27 @@ These attributes have default values of: .. code:: python - change_form_template_extends = 'admin/change_form.html' - change_list_template_extends = 'admin/change_list.html' + change_form_template_extends = 'admin/change_form.html' + change_list_template_extends = 'admin/change_list.html' -If you need to extend the inline change form templates, you'll need to -select the right one, depending on your version of Django. For Django -1.5.x or below, you'll need to extend one of the following: +If you need to extend the inline change form templates, you’ll need to +select the right one, depending on your version of Django. For 1.10.x or +below, you’ll need to extend one of the following: :: - templates/adminsortable/edit_inline/stacked-1.5.x.html - templates/adminsortable/edit_inline/tabular-inline-1.5.x.html + templates/adminsortable/edit_inline/stacked-1.10.x.html + templates/adminsortable/edit_inline/tabular-inline-1.10.x.html -For Django 1.6.x, extend: +otherwise, extend: :: templates/adminsortable/edit_inline/stacked.html templates/adminsortable/edit_inline/tabular.html -A Special Note About Stacked Inlines... -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +A Special Note About Stacked Inlines… +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The height of a stacked inline model can dynamically increase, which can make them difficult to sort. If you anticipate the height of a stacked @@ -539,7 +545,7 @@ SortableTabularInline instead. Django-CMS integration ~~~~~~~~~~~~~~~~~~~~~~ -Django-CMS plugins use their own change form, and thus won't +Django-CMS plugins use their own change form, and thus won’t automatically include the necessary JavaScript for django-admin-sortable to work. Fortunately, this is easy to resolve, as the ``CMSPlugin`` class allows a change form template to be specified: @@ -569,16 +575,17 @@ class allows a change form template to be specified: The contents of ``sortable-stacked-inline-change-form.html`` at a minimum need to extend the extrahead block with: -.. code:: html +.. code:: html+django {% extends "admin/cms/page/plugin_change_form.html" %} {% load static from staticfiles %} {% block extrahead %} {{ block.super }} - - - + + + + {% endblock extrahead %} @@ -587,21 +594,54 @@ Sorting within Django-CMS is really only feasible for inline models of a plugin as Django-CMS already includes sorting for plugin instances. For tabular inlines, just substitute: -.. code:: html +.. code:: html+django - + with: -.. code:: html +.. code:: html+django - + + +Notes +~~~~~ + +From ``django-cms 3.x`` the path of change_form.html has changed. +Replace the follwing line: + +.. code:: html+django + + {% extends "admin/cms/page/plugin_change_form.html" %} + +with + +.. code:: html+django + + {% extends "admin/cms/page/plugin/change_form.html" %} + +From ``django-admin-sortable 2.0.13`` the ``jquery.django-csrf.js`` was +removed and you have to include the snippet-template. Change the +following line: + +.. code:: html+django + + + +to + +.. code:: html+django + + {% include 'adminsortable/csrf/jquery.django-csrf.html' with csrf_cookie_name='csrftoken' %} + +Please note, if you change the ``CSRF_COOKIE_NAME`` you have to adjust +``csrf_cookie_name='YOUR_CSRF_COOKIE_NAME'`` Rationale ~~~~~~~~~ Other projects have added drag-and-drop ordering to the ChangeList view, -however this introduces a couple of problems... +however this introduces a couple of problems… - The ChangeList view supports pagination, which makes drag-and-drop ordering across pages impossible. @@ -617,13 +657,11 @@ Status django-admin-sortable is currently used in production. -What's new in 2.0.21? -~~~~~~~~~~~~~~~~~~~~~ +What’s new in 2.1.4? +~~~~~~~~~~~~~~~~~~~~ -- Fixed a regression introduced by `Pull Request - 143 `__ - which caused models sortable by a foriegn key to not persist the sort - order correctly. +- Improved performance on large data sets. Credit to + `mrmachine `__. Future ~~~~~~ @@ -637,5 +675,9 @@ License django-admin-sortable is released under the Apache Public License v2. -.. |Build Status| image:: https://travis-ci.org/iambrandontaylor/django-admin-sortable.svg?branch=master - :target: https://travis-ci.org/iambrandontaylor/django-admin-sortable +.. |PyPI version| image:: https://img.shields.io/pypi/v/django-admin-sortable.svg + :target: https://pypi.python.org/pypi/django-admin-sortable +.. |Python versions| image:: https://img.shields.io/pypi/pyversions/django-admin-sortable.svg + :target: https://pypi.python.org/pypi/django-admin-sortable +.. |Build Status| image:: https://travis-ci.org/alsoicode/django-admin-sortable.svg?branch=master + :target: https://travis-ci.org/alsoicode/django-admin-sortable diff --git a/adminsortable/__init__.py b/adminsortable/__init__.py index eda5d99..cc24828 100644 --- a/adminsortable/__init__.py +++ b/adminsortable/__init__.py @@ -1,4 +1,4 @@ -VERSION = (2, 0, 21) +VERSION = (2, 1, 4) DEV_N = None diff --git a/adminsortable/admin.py b/adminsortable/admin.py index 7257a34..3bad43e 100644 --- a/adminsortable/admin.py +++ b/adminsortable/admin.py @@ -3,24 +3,11 @@ import json from django import VERSION from django.conf import settings - -try: - from django.conf.urls import url -except ImportError: - # Django < 1.4 - from django.conf.urls.defaults import url - +from django.conf.urls import url from django.contrib.admin import ModelAdmin, TabularInline, StackedInline from django.contrib.admin.options import InlineModelAdmin - -try: - from django.contrib.contenttypes.admin import (GenericStackedInline, - GenericTabularInline) -except: - # Django < 1.7 - from django.contrib.contenttypes.generic import (GenericStackedInline, - GenericTabularInline) - +from django.contrib.contenttypes.admin import (GenericStackedInline, + GenericTabularInline) from django.contrib.contenttypes.models import ContentType from django.core.exceptions import PermissionDenied from django.http import HttpResponse, Http404 @@ -51,13 +38,7 @@ class SortableAdminBase(object): its sort order can be changed. This view adds a link to the object_tools block to take people to the view to change the sorting. """ - - try: - qs_method = getattr(self, 'get_queryset', self.queryset) - except AttributeError: - qs_method = self.get_queryset - - if get_is_sortable(qs_method(request)): + if get_is_sortable(self.get_queryset(request)): self.change_list_template = \ self.sortable_change_list_with_sort_link_template self.is_sortable = True @@ -101,12 +82,7 @@ class SortableAdmin(SortableAdminBase, ModelAdmin): def get_urls(self): urls = super(SortableAdmin, self).get_urls() - opts = self.model._meta - try: - info = opts.app_label, opts.model_name - except AttributeError: - # Django < 1.7 - info = opts.app_label, opts.model_name + info = self.model._meta.app_label, self.model._meta.model_name # this ajax view changes the order of instances of the model type admin_do_sorting_url = url( @@ -126,6 +102,24 @@ class SortableAdmin(SortableAdminBase, ModelAdmin): ] + urls return urls + def get_sort_view_queryset(self, request, sortable_by_expression): + """ + Return a queryset, optionally filtered based on request and + `sortable_by_expression` to be used in the sort view. + """ + # get sort group index from querystring if present + sort_filter_index = request.GET.get('sort_filter') + + filters = {} + if sort_filter_index: + try: + filters = self.model.sorting_filters[int(sort_filter_index)][1] + except (IndexError, ValueError): + pass + + # Apply any sort filters to create a subset of sortable objects + return self.get_queryset(request).filter(**filters) + def sort_view(self, request): """ Custom admin view that displays the objects as a list whose sort @@ -139,23 +133,6 @@ class SortableAdmin(SortableAdminBase, ModelAdmin): jquery_lib_path = 'admin/js/jquery.js' if VERSION < (1, 9) \ else 'admin/js/vendor/jquery/jquery.js' - # get sort group index from querystring if present - sort_filter_index = request.GET.get('sort_filter') - - filters = {} - if sort_filter_index: - try: - filters = self.model.sorting_filters[int(sort_filter_index)][1] - except (IndexError, ValueError): - pass - - # Apply any sort filters to create a subset of sortable objects - try: - qs_method = getattr(self, 'get_queryset', self.queryset) - except AttributeError: - qs_method = self.get_queryset - objects = qs_method(request).filter(**filters) - # Determine if we need to regroup objects relative to a # foreign key specified on the model class that is extending Sortable. # Legacy support for 'sortable_by' defined as a model property @@ -169,7 +146,11 @@ class SortableAdmin(SortableAdminBase, ModelAdmin): for field in self.model._meta.fields: if isinstance(field, SortableForeignKey): - sortable_by_fk = field.rel.to + try: + sortable_by_fk = field.remote_field.model + except AttributeError: + # Django < 1.9 + sortable_by_fk = field.rel.to sortable_by_field_name = field.name.lower() sortable_by_class_is_sortable = sortable_by_fk.objects.count() >= 2 @@ -199,6 +180,8 @@ class SortableAdmin(SortableAdminBase, ModelAdmin): sortable_by_class_display_name = \ sortable_by_class_is_sortable = None + objects = self.get_sort_view_queryset(request, sortable_by_expression) + if sortable_by_property or sortable_by_fk: # Order the objects by the property they are sortable by, # then by the order, otherwise the regroup @@ -206,9 +189,6 @@ class SortableAdmin(SortableAdminBase, ModelAdmin): try: order_field_name = opts.model._meta.ordering[0] - except (AttributeError, IndexError): - # for Django 1.5.x - order_field_name = opts.ordering[0] except (AttributeError, IndexError): order_field_name = 'order' @@ -301,8 +281,11 @@ class SortableAdmin(SortableAdminBase, ModelAdmin): for index in indexes: obj = objects_dict.get(index) - setattr(obj, order_field_name, start_index) - obj.save() + # perform the update only if the order field has changed + if getattr(obj, order_field_name) != start_index: + setattr(obj, order_field_name, start_index) + # only update the object's order field + obj.save(update_fields=(order_field_name,)) start_index += step response = {'objects_sorted': True} except (KeyError, IndexError, klass.DoesNotExist, @@ -329,27 +312,18 @@ class SortableInlineBase(SortableAdminBase, InlineModelAdmin): ' (or Sortable for legacy implementations)') def get_queryset(self, request): - if VERSION < (1, 6): - qs = super(SortableInlineBase, self).queryset(request) - else: - qs = super(SortableInlineBase, self).get_queryset(request) - + qs = super(SortableInlineBase, self).get_queryset(request) if get_is_sortable(qs): self.model.is_sortable = True else: self.model.is_sortable = False return qs - if VERSION < (1, 6): - queryset = get_queryset - class SortableTabularInline(TabularInline, SortableInlineBase): """Custom template that enables sorting for tabular inlines""" if VERSION >= (1, 10): template = 'adminsortable/edit_inline/tabular-1.10.x.html' - elif VERSION < (1, 6): - template = 'adminsortable/edit_inline/tabular-1.5.x.html' else: template = 'adminsortable/edit_inline/tabular.html' @@ -358,8 +332,6 @@ class SortableStackedInline(StackedInline, SortableInlineBase): """Custom template that enables sorting for stacked inlines""" if VERSION >= (1, 10): template = 'adminsortable/edit_inline/stacked-1.10.x.html' - elif VERSION < (1, 6): - template = 'adminsortable/edit_inline/stacked-1.5.x.html' else: template = 'adminsortable/edit_inline/stacked.html' @@ -368,8 +340,6 @@ class SortableGenericTabularInline(GenericTabularInline, SortableInlineBase): """Custom template that enables sorting for tabular inlines""" if VERSION >= (1, 10): template = 'adminsortable/edit_inline/tabular-1.10.x.html' - elif VERSION < (1, 6): - template = 'adminsortable/edit_inline/tabular-1.5.x.html' else: template = 'adminsortable/edit_inline/tabular.html' @@ -378,7 +348,5 @@ class SortableGenericStackedInline(GenericStackedInline, SortableInlineBase): """Custom template that enables sorting for stacked inlines""" if VERSION >= (1, 10): template = 'adminsortable/edit_inline/stacked-1.10.x.html' - elif VERSION < (1, 6): - template = 'adminsortable/edit_inline/stacked-1.5.x.html' else: template = 'adminsortable/edit_inline/stacked.html' diff --git a/adminsortable/fields.py b/adminsortable/fields.py index 380f555..3376f12 100644 --- a/adminsortable/fields.py +++ b/adminsortable/fields.py @@ -7,14 +7,4 @@ class SortableForeignKey(ForeignKey): This field replaces previous functionality where `sortable_by` was defined as a model property that specified another model class. """ - - def south_field_triple(self): - try: - from south.modelsinspector import introspector - cls_name = '{0}.{1}'.format( - self.__class__.__module__, - self.__class__.__name__) - args, kwargs = introspector(self) - return cls_name, args, kwargs - except ImportError: - pass + pass diff --git a/adminsortable/locale/lv/LC_MESSAGES/django.po b/adminsortable/locale/lv/LC_MESSAGES/django.po new file mode 100644 index 0000000..4ed9940 --- /dev/null +++ b/adminsortable/locale/lv/LC_MESSAGES/django.po @@ -0,0 +1,51 @@ +msgid "" +msgstr "" +"Project-Id-Version: adminsortable\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2011-09-22 15:42+0200\n" +"PO-Revision-Date: 2018-02-08 22:47+0200\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Last-Translator: Pēteris \n" +"Language-Team: \n" +"Language: lv\n" +"X-Generator: Poedit 1.8.7.1\n" + +#: templates/adminsortable/change_list.html:15 +#, python-format +msgid "Drag and drop %(model)s to change display order" +msgstr "Velc un novieto %(model)s, lai mainītu attēlošanas secību" + +#: templates/adminsortable/change_list.html:25 +#, python-format +msgid "Reorder" +msgstr "Pārkārtot" + +#: templates/adminsortable/change_list.html:32 +#, python-format +msgid "Drag and drop %(sort_type)s %(model)s to change their order." +msgstr "Velc un novieto %(sort_type)s %(model)s, lai mainītu to secību." + +#: templates/adminsortable/change_list.html:34 +#, python-format +msgid "Drag and drop %(model)s to change their order." +msgstr "Velc un novieto %(model)s, lai mainītu attēlošanas secību." + +#: templates/adminsortable/change_list.html:39 +#, python-format +msgid "" +"You may also drag and drop %(sortable_by_class_display_name)s to change " +"their order." +msgstr "" +"Tu vari arī vilt un pārvieetot %(sortable_by_class_display_name)s, lai " +"mainītu secību." + +#: templates/adminsortable/change_list.html:50 +#, python-format +msgid "Return to %(model)s" +msgstr "Atgriezties pie %(model)s" + +#: templates/adminsortable/change_list_with_sort_link.html:6 +msgid "Change Order" +msgstr "Mainīt secību" diff --git a/adminsortable/locale/nb/LC_MESSAGES/django.mo b/adminsortable/locale/nb/LC_MESSAGES/django.mo new file mode 100644 index 0000000..092453a Binary files /dev/null and b/adminsortable/locale/nb/LC_MESSAGES/django.mo differ diff --git a/adminsortable/locale/nb/LC_MESSAGES/django.po b/adminsortable/locale/nb/LC_MESSAGES/django.po new file mode 100644 index 0000000..4f6366c --- /dev/null +++ b/adminsortable/locale/nb/LC_MESSAGES/django.po @@ -0,0 +1,51 @@ +msgid "" +msgstr "" +"Project-Id-Version: adminsortable\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2011-09-22 15:42+0200\n" +"PO-Revision-Date: 2018-02-05 17:24+0100\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Last-Translator: Simen Heggestøyl \n" +"Language-Team: \n" +"Language: nb\n" +"X-Generator: Poedit 2.0.5\n" + +#: templates/adminsortable/change_list.html:15 +#, python-format +msgid "Drag and drop %(model)s to change display order" +msgstr "Dra og slipp %(model)s for å endre visningsrekkefølgen" + +#: templates/adminsortable/change_list.html:25 +#, python-format +msgid "Reorder" +msgstr "Endre rekkefølge" + +#: templates/adminsortable/change_list.html:32 +#, python-format +msgid "Drag and drop %(sort_type)s %(model)s to change their order." +msgstr "Dra og slipp %(sort_type)s %(model)s for å endre rekkefølgen deres." + +#: templates/adminsortable/change_list.html:34 +#, python-format +msgid "Drag and drop %(model)s to change their order." +msgstr "Dra og slipp %(model)s for å endre rekkefølgen deres." + +#: templates/adminsortable/change_list.html:39 +#, python-format +msgid "" +"You may also drag and drop %(sortable_by_class_display_name)s to change " +"their order." +msgstr "" +"Du kan også dra og slippe %(sortable_by_class_display_name)s for å endre " +"rekkefølgen deres." + +#: templates/adminsortable/change_list.html:50 +#, python-format +msgid "Return to %(model)s" +msgstr "Tilbake til %(model)s" + +#: templates/adminsortable/change_list_with_sort_link.html:6 +msgid "Change Order" +msgstr "Endre rekkefølge" diff --git a/adminsortable/static/adminsortable/css/admin.sortable.css b/adminsortable/static/adminsortable/css/admin.sortable.css index e03ef81..e1c857c 100644 --- a/adminsortable/static/adminsortable/css/admin.sortable.css +++ b/adminsortable/static/adminsortable/css/admin.sortable.css @@ -19,10 +19,15 @@ #sortable ul li { overflow: auto; + margin-bottom: 8px; margin-left: 0; display: block; } +#sortable ul li:last-child { + margin-bottom: 0; +} + #sortable .sortable { list-style: none; diff --git a/adminsortable/static/adminsortable/js/jquery.ui.touch-punch.min.js b/adminsortable/static/adminsortable/js/jquery.ui.touch-punch.min.js new file mode 100644 index 0000000..31272ce --- /dev/null +++ b/adminsortable/static/adminsortable/js/jquery.ui.touch-punch.min.js @@ -0,0 +1,11 @@ +/*! + * jQuery UI Touch Punch 0.2.3 + * + * Copyright 2011–2014, Dave Furfero + * Dual licensed under the MIT or GPL Version 2 licenses. + * + * Depends: + * jquery.ui.widget.js + * jquery.ui.mouse.js + */ +!function(a){function f(a,b){if(!(a.originalEvent.touches.length>1)){a.preventDefault();var c=a.originalEvent.changedTouches[0],d=document.createEvent("MouseEvents");d.initMouseEvent(b,!0,!0,window,1,c.screenX,c.screenY,c.clientX,c.clientY,!1,!1,!1,!1,0,null),a.target.dispatchEvent(d)}}if(a.support.touch="ontouchend"in document,a.support.touch){var e,b=a.ui.mouse.prototype,c=b._mouseInit,d=b._mouseDestroy;b._touchStart=function(a){var b=this;!e&&b._mouseCapture(a.originalEvent.changedTouches[0])&&(e=!0,b._touchMoved=!1,f(a,"mouseover"),f(a,"mousemove"),f(a,"mousedown"))},b._touchMove=function(a){e&&(this._touchMoved=!0,f(a,"mousemove"))},b._touchEnd=function(a){e&&(f(a,"mouseup"),f(a,"mouseout"),this._touchMoved||f(a,"click"),e=!1)},b._mouseInit=function(){var b=this;b.element.bind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),c.call(b)},b._mouseDestroy=function(){var b=this;b.element.unbind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),d.call(b)}}}(jQuery); \ No newline at end of file diff --git a/adminsortable/templates/adminsortable/change_form.html b/adminsortable/templates/adminsortable/change_form.html index f1c190d..65763cb 100644 --- a/adminsortable/templates/adminsortable/change_form.html +++ b/adminsortable/templates/adminsortable/change_form.html @@ -8,6 +8,7 @@ {% if has_sortable_tabular_inlines or has_sortable_stacked_inlines %} + {% include 'adminsortable/csrf/jquery.django-csrf.html' with csrf_cookie_name=csrf_cookie_name %} {% endif %} diff --git a/adminsortable/templates/adminsortable/change_list.html b/adminsortable/templates/adminsortable/change_list.html index 65cd3f2..3be48ab 100644 --- a/adminsortable/templates/adminsortable/change_list.html +++ b/adminsortable/templates/adminsortable/change_list.html @@ -1,5 +1,5 @@ {% extends "admin/base_site.html" %} -{% load i18n admin_urls static admin_list adminsortable_tags %} +{% load i18n admin_urls static admin_list %} {% block extrastyle %} {{ block.super }} @@ -26,6 +26,7 @@ + {% include 'adminsortable/csrf/jquery.django-csrf.html' with csrf_cookie_name=csrf_cookie_name %} {% endblock %} @@ -74,20 +75,20 @@ {% block content %}
{% block object-tools %} - - {% endblock %} + + {% endblock %} {% if objects %}
{% if group_expression %} - {% render_nested_sortable_objects objects group_expression %} + {% include "adminsortable/shared/nested_objects.html" %} {% else %} - {% render_sortable_objects objects %} + {% include "adminsortable/shared/objects.html" %} {% endif %} {% csrf_token %}
diff --git a/adminsortable/templates/adminsortable/csrf/jquery.django-csrf.html b/adminsortable/templates/adminsortable/csrf/jquery.django-csrf.html index 24fb6c3..b9488a8 100644 --- a/adminsortable/templates/adminsortable/csrf/jquery.django-csrf.html +++ b/adminsortable/templates/adminsortable/csrf/jquery.django-csrf.html @@ -16,7 +16,7 @@ return cookieValue; } - var csrftoken = getCookie('{{ csrf_cookie_name }}'); + var csrftoken = '{{ csrf_token }}' || getCookie('{{ csrf_cookie_name }}'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection diff --git a/adminsortable/templates/adminsortable/edit_inline/stacked-1.5.x.html b/adminsortable/templates/adminsortable/edit_inline/stacked-1.5.x.html deleted file mode 100644 index c34182d..0000000 --- a/adminsortable/templates/adminsortable/edit_inline/stacked-1.5.x.html +++ /dev/null @@ -1,92 +0,0 @@ -{% load i18n admin_modify adminsortable_tags admin_urls %} -{% load static from staticfiles %} -
-

{{ inline_admin_formset.opts.verbose_name_plural|title }} {% if inline_admin_formset.formset.initial_form_count > 1 %} - {% trans "drag and drop to change order" %}{% endif %}

-{{ inline_admin_formset.formset.management_form }} -{{ inline_admin_formset.formset.non_form_errors }} - -{% for inline_admin_form in inline_admin_formset %}
-

- {% if inline_admin_form.original %} - {% with initial_forms_count=inline_admin_formset.formset.management_form.INITIAL_FORMS.value %} - - {% endwith %} - {% endif %} - {{ inline_admin_formset.opts.verbose_name|title }}: {% if inline_admin_form.original %}{{ inline_admin_form.original }}{% else %}#{{ forloop.counter }}{% endif %} - {% if inline_admin_form.show_url %}{% trans "View on site" %}{% endif %} - {% if inline_admin_formset.formset.can_delete and inline_admin_form.original %}{{ inline_admin_form.deletion_field.field }} {{ inline_admin_form.deletion_field.label_tag }}{% endif %} -

- {% if inline_admin_form.form.non_field_errors %}{{ inline_admin_form.form.non_field_errors }}{% endif %} - {% for fieldset in inline_admin_form %} - {% include "admin/includes/fieldset.html" %} - {% endfor %} - {% if inline_admin_form.has_auto_field %}{{ inline_admin_form.pk_field.field }}{% endif %} - {{ inline_admin_form.fk_field.field }} - {% if inline_admin_form.original %} - - {% endif %} -
{% endfor %} -
- - diff --git a/adminsortable/templates/adminsortable/edit_inline/tabular-1.5.x.html b/adminsortable/templates/adminsortable/edit_inline/tabular-1.5.x.html deleted file mode 100644 index bdc8348..0000000 --- a/adminsortable/templates/adminsortable/edit_inline/tabular-1.5.x.html +++ /dev/null @@ -1,136 +0,0 @@ -{% load i18n admin_modify adminsortable_tags admin_urls %} -{% load static from staticfiles %} -
- -
- - diff --git a/adminsortable/templates/adminsortable/shared/list_items.html b/adminsortable/templates/adminsortable/shared/list_items.html index 29df030..21f9005 100644 --- a/adminsortable/templates/adminsortable/shared/list_items.html +++ b/adminsortable/templates/adminsortable/shared/list_items.html @@ -1,9 +1,8 @@ -{% load adminsortable_tags %} {% with list_objects_length=list_objects|length %} {% for object in list_objects %}
  • {% if list_objects_length > 1 %} - {% render_object_rep object forloop %} + {% include "adminsortable/shared/object_rep.html" %} {% else %} {{ object }} {% endif %} diff --git a/adminsortable/templates/adminsortable/shared/nested_objects.html b/adminsortable/templates/adminsortable/shared/nested_objects.html index 8ef74d9..cf0483b 100644 --- a/adminsortable/templates/adminsortable/shared/nested_objects.html +++ b/adminsortable/templates/adminsortable/shared/nested_objects.html @@ -1,4 +1,4 @@ -{% load django_template_additions adminsortable_tags %} +{% load django_template_additions %} {% dynamic_regroup objects by group_expression as regrouped_objects %} {% if regrouped_objects %}
      @@ -6,7 +6,7 @@ {% with object=regrouped_object.grouper %} {% if object %}
    • {% if sortable_by_class_is_sortable %} - {% render_object_rep object forloop %} + {% include "adminsortable/shared/object_rep.html" %} {% else %} {{ object }} {% endif %} @@ -14,7 +14,7 @@ {% if regrouped_object.list %} {% with regrouped_object_list_length=regrouped_object.list|length %}
        1 %}class="sortable"{% endif %}> - {% render_list_items regrouped_object.list %} + {% include "adminsortable/shared/list_items.html" with list_objects=regrouped_object.list %}
      {% endwith %} {% endif %} diff --git a/adminsortable/templates/adminsortable/shared/object_rep.html b/adminsortable/templates/adminsortable/shared/object_rep.html index 72c13cd..88e6c6f 100644 --- a/adminsortable/templates/adminsortable/shared/object_rep.html +++ b/adminsortable/templates/adminsortable/shared/object_rep.html @@ -1,4 +1,4 @@ -{% load adminsortable_tags admin_urls %} +{% load admin_urls %}
      diff --git a/adminsortable/templates/adminsortable/shared/objects.html b/adminsortable/templates/adminsortable/shared/objects.html index 8f0af7c..52e403d 100644 --- a/adminsortable/templates/adminsortable/shared/objects.html +++ b/adminsortable/templates/adminsortable/shared/objects.html @@ -1,7 +1,5 @@ -{% load adminsortable_tags %} - {% if objects %}
        - {% render_list_items objects %} + {% include "adminsortable/shared/list_items.html" with list_objects=objects %}
      {% endif %} \ No newline at end of file diff --git a/adminsortable/templatetags/adminsortable_tags.py b/adminsortable/templatetags/adminsortable_tags.py deleted file mode 100644 index bbed9a0..0000000 --- a/adminsortable/templatetags/adminsortable_tags.py +++ /dev/null @@ -1,35 +0,0 @@ -from django import template - -register = template.Library() - - -@register.simple_tag(takes_context=True) -def render_sortable_objects(context, objects, - sortable_objects_template='adminsortable/shared/objects.html'): - context.update({'objects': objects}) - tmpl = template.loader.get_template(sortable_objects_template) - return tmpl.render(context) - - -@register.simple_tag(takes_context=True) -def render_nested_sortable_objects(context, objects, group_expression, - sortable_nested_objects_template='adminsortable/shared/nested_objects.html'): - context.update({'objects': objects, 'group_expression': group_expression}) - tmpl = template.loader.get_template(sortable_nested_objects_template) - return tmpl.render(context) - - -@register.simple_tag(takes_context=True) -def render_list_items(context, list_objects, - sortable_list_items_template='adminsortable/shared/list_items.html'): - context.update({'list_objects': list_objects}) - tmpl = template.loader.get_template(sortable_list_items_template) - return tmpl.render(context) - - -@register.simple_tag(takes_context=True) -def render_object_rep(context, obj, forloop, - sortable_object_rep_template='adminsortable/shared/object_rep.html'): - context.update({'object': obj, 'forloop': forloop}) - tmpl = template.loader.get_template(sortable_object_rep_template) - return tmpl.render(context) diff --git a/adminsortable/templatetags/django_template_additions.py b/adminsortable/templatetags/django_template_additions.py index c05f349..0729bb3 100644 --- a/adminsortable/templatetags/django_template_additions.py +++ b/adminsortable/templatetags/django_template_additions.py @@ -2,11 +2,6 @@ from itertools import groupby import django from django import template -try: - from django import TemplateSyntaxError -except ImportError: - #support for django 1.3 - from django.template.base import TemplateSyntaxError register = template.Library() @@ -64,14 +59,15 @@ def dynamic_regroup(parser, token): """ firstbits = token.contents.split(None, 3) if len(firstbits) != 4: - raise TemplateSyntaxError("'regroup' tag takes five arguments") + raise template.TemplateSyntaxError("'regroup' tag takes five arguments") target = parser.compile_filter(firstbits[1]) if firstbits[2] != 'by': - raise TemplateSyntaxError("second argument to 'regroup' tag must be 'by'") + raise template.TemplateSyntaxError( + "second argument to 'regroup' tag must be 'by'") lastbits_reversed = firstbits[3][::-1].split(None, 2) if lastbits_reversed[1][::-1] != 'as': - raise TemplateSyntaxError("next-to-last argument to 'regroup' tag must" - " be 'as'") + raise template.TemplateSyntaxError( + "next-to-last argument to 'regroup' tag must be 'as'") expression = lastbits_reversed[2][::-1] var_name = lastbits_reversed[0][::-1] @@ -80,7 +76,7 @@ def dynamic_regroup(parser, token): return DynamicRegroupNode(target, parser, expression, var_name) -@register.assignment_tag +@register.simple_tag def get_django_version(): version = django.VERSION return {'major': version[0], 'minor': version[1]} diff --git a/sample_project/database/test_project.sqlite b/sample_project/database/test_project.sqlite index b09cb9c..d439e4a 100644 Binary files a/sample_project/database/test_project.sqlite and b/sample_project/database/test_project.sqlite differ diff --git a/sample_project/sample_project/settings.py b/sample_project/sample_project/settings.py index ceb7009..151d35e 100644 --- a/sample_project/sample_project/settings.py +++ b/sample_project/sample_project/settings.py @@ -1,6 +1,8 @@ # Django settings for test_project project. import os +import django + def map_path(directory_name): return os.path.join(os.path.dirname(__file__), @@ -8,7 +10,6 @@ def map_path(directory_name): DEBUG = True -TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), @@ -91,44 +92,36 @@ STATICFILES_FINDERS = ( # Make this unique, and don't share it with anybody. SECRET_KEY = '8**a!c8$1x)p@j2pj0yq!*v+dzp24g*$918ws#x@k+gf%0%rct' -# List of callables that know how to import templates from various sources. -TEMPLATE_LOADERS = ( - 'django.template.loaders.filesystem.Loader', - 'django.template.loaders.app_directories.Loader', -) - -MIDDLEWARE_CLASSES = ( - 'django.middleware.common.CommonMiddleware', +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', - # Uncomment the next line for simple clickjacking protection: 'django.middleware.clickjacking.XFrameOptionsMiddleware', -) +] + +if django.VERSION < (1, 10): + MIDDLEWARE_CLASSES = MIDDLEWARE ROOT_URLCONF = 'sample_project.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'sample_project.wsgi.application' -TEMPLATE_DIRS = ( - map_path('templates'), -) - TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': TEMPLATE_DIRS, + 'DIRS': [ + map_path('templates'), + ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ - 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', - 'django.template.context_processors.i18n', - 'django.template.context_processors.media', - 'django.template.context_processors.static', - 'django.template.context_processors.tz', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, @@ -146,7 +139,7 @@ INSTALLED_APPS = ( 'django.contrib.admindocs', 'adminsortable', - 'app', + 'samples', ) # A sample logging configuration. The only tangible logging @@ -177,3 +170,21 @@ LOGGING = { }, } } + +# Password validation +# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] diff --git a/sample_project/sample_project/urls.py b/sample_project/sample_project/urls.py index 5abb2fc..2071700 100644 --- a/sample_project/sample_project/urls.py +++ b/sample_project/sample_project/urls.py @@ -1,18 +1,21 @@ -from django.conf.urls import include, url +"""django2_app URL Configuration -# Uncomment the next two lines to enable the admin: +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/2.0/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" from django.contrib import admin -admin.autodiscover() - +from django.urls import path urlpatterns = [ - # Examples: - # url(r'^$', 'test_project.views.home', name='home'), - # url(r'^test_project/', include('test_project.foo.urls')), - - # Uncomment the admin/doc line below to enable admin documentation: - url(r'^admin/doc/', include('django.contrib.admindocs.urls')), - - # Uncomment the next line to enable the admin: - url(r'^admin/', include(admin.site.urls)), + path('admin/', admin.site.urls), ] diff --git a/sample_project/sample_project/utils.py b/sample_project/sample_project/utils.py deleted file mode 100644 index 4178ad9..0000000 --- a/sample_project/sample_project/utils.py +++ /dev/null @@ -1,6 +0,0 @@ -import os - - -def map_path(directory_name): - return os.path.join(os.path.dirname(__file__), - '../' + directory_name).replace('\\', '/') diff --git a/sample_project/sample_project/wsgi.py b/sample_project/sample_project/wsgi.py index 43ff066..c54b86f 100644 --- a/sample_project/sample_project/wsgi.py +++ b/sample_project/sample_project/wsgi.py @@ -1,32 +1,15 @@ """ -WSGI config for test_project project. +WSGI config for django2_app project. -This module contains the WSGI application used by Django's development server -and any production WSGI deployments. It should expose a module-level variable -named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover -this application via the ``WSGI_APPLICATION`` setting. - -Usually you will have the standard Django WSGI application here, but it also -might make sense to replace the whole Django WSGI application with a custom one -that later delegates to the Django one. For example, you could introduce WSGI -middleware here, or combine a Django application with an application of another -framework. +It exposes the WSGI callable as a module-level variable named ``application``. +For more information on this file, see +https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/ """ import os -# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks -# if running multiple sites in the same mod_wsgi process. To fix this, use -# mod_wsgi daemon mode with each site in its own daemon process, or use -# os.environ["DJANGO_SETTINGS_MODULE"] = "test_project.settings" -os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_project.settings") - -# This application object is used by any WSGI server configured to use this -# file. This includes Django's development server, if the WSGI_APPLICATION -# setting points here. from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_project.settings") application = get_wsgi_application() -# Apply WSGI middleware here. -# from helloworld.wsgi import HelloWorldApplication -# application = HelloWorldApplication(application) diff --git a/sample_project/app/__init__.py b/sample_project/samples/__init__.py similarity index 100% rename from sample_project/app/__init__.py rename to sample_project/samples/__init__.py diff --git a/sample_project/app/admin.py b/sample_project/samples/admin.py similarity index 91% rename from sample_project/app/admin.py rename to sample_project/samples/admin.py index cba42f8..ec18418 100644 --- a/sample_project/app/admin.py +++ b/sample_project/samples/admin.py @@ -4,7 +4,7 @@ from adminsortable.admin import (SortableAdmin, SortableTabularInline, SortableStackedInline, SortableGenericStackedInline, NonSortableParentAdmin) from adminsortable.utils import get_is_sortable -from app.models import (Category, Widget, Project, Credit, Note, GenericNote, +from .models import (Category, Widget, Project, Credit, Note, GenericNote, Component, Person, NonSortableCategory, SortableCategoryWidget, SortableNonInlineCategory, NonSortableCredit, NonSortableNote, CustomWidget, CustomWidgetComponent, BackwardCompatibleWidget) @@ -26,8 +26,8 @@ class ComponentInline(SortableStackedInline): # ) model = Component - def queryset(self, request): - qs = super(ComponentInline, self).queryset( + def get_queryset(self, request): + qs = super(ComponentInline, self).get_queryset( request).exclude(title__icontains='2') if get_is_sortable(qs): self.model.is_sortable = True @@ -37,14 +37,14 @@ class ComponentInline(SortableStackedInline): class WidgetAdmin(SortableAdmin): - def queryset(self, request): + def get_queryset(self, request): """ A simple example demonstrating that adminsortable works even in situations where you need to filter the queryset in admin. Here, we are just filtering out `widget` instances with an pk higher than 3 """ - qs = super(WidgetAdmin, self).queryset(request) + qs = super(WidgetAdmin, self).get_queryset(request) return qs.filter(id__lte=3) inlines = [ComponentInline] diff --git a/sample_project/samples/apps.py b/sample_project/samples/apps.py new file mode 100644 index 0000000..ea7abac --- /dev/null +++ b/sample_project/samples/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class SamplesConfig(AppConfig): + name = 'samples' diff --git a/sample_project/samples/migrations/0001_initial.py b/sample_project/samples/migrations/0001_initial.py new file mode 100644 index 0000000..94ea157 --- /dev/null +++ b/sample_project/samples/migrations/0001_initial.py @@ -0,0 +1,235 @@ +# Generated by Django 2.0 on 2017-12-05 02:55 + +import adminsortable.fields +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('contenttypes', '0002_remove_content_type_name'), + ] + + operations = [ + migrations.CreateModel( + name='BackwardCompatibleWidget', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('order', models.PositiveIntegerField(db_index=True, default=0, editable=False)), + ('title', models.CharField(max_length=50)), + ], + options={ + 'verbose_name': 'Backward Compatible Widget', + 'verbose_name_plural': 'Backward Compatible Widgets', + 'ordering': ['order'], + 'abstract': False, + }, + ), + migrations.CreateModel( + name='Category', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=50)), + ('order', models.PositiveIntegerField(default=0)), + ], + options={ + 'verbose_name_plural': 'Categories', + 'ordering': ['order'], + }, + ), + migrations.CreateModel( + name='Component', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=50)), + ('order', models.PositiveIntegerField(default=0, editable=False)), + ], + options={ + 'ordering': ['order'], + }, + ), + migrations.CreateModel( + name='Credit', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('first_name', models.CharField(help_text='Given name', max_length=30)), + ('last_name', models.CharField(help_text='Family name', max_length=30)), + ('order', models.PositiveIntegerField(default=0, editable=False)), + ], + options={ + 'ordering': ['order'], + }, + ), + migrations.CreateModel( + name='CustomWidget', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=50)), + ('custom_order_field', models.PositiveIntegerField(db_index=True, default=0, editable=False)), + ], + options={ + 'verbose_name': 'Custom Widget', + 'verbose_name_plural': 'Custom Widgets', + 'ordering': ['custom_order_field'], + }, + ), + migrations.CreateModel( + name='CustomWidgetComponent', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=50)), + ('widget_order', models.PositiveIntegerField(db_index=True, default=0, editable=False)), + ('custom_widget', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='samples.CustomWidget')), + ], + options={ + 'verbose_name': 'Custom Widget Component', + 'verbose_name_plural': 'Custom Widget Components', + 'ordering': ['widget_order'], + }, + ), + migrations.CreateModel( + name='GenericNote', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=50)), + ('object_id', models.PositiveIntegerField(verbose_name='Content id')), + ('order', models.PositiveIntegerField(default=0, editable=False)), + ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='generic_notes', to='contenttypes.ContentType', verbose_name='Content type')), + ], + options={ + 'ordering': ['order'], + }, + ), + migrations.CreateModel( + name='NonSortableCategory', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=50)), + ], + options={ + 'verbose_name': 'Non-Sortable Category', + 'verbose_name_plural': 'Non-Sortable Categories', + 'abstract': False, + }, + ), + migrations.CreateModel( + name='NonSortableCredit', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('first_name', models.CharField(help_text='Given name', max_length=30)), + ('last_name', models.CharField(help_text='Family name', max_length=30)), + ], + ), + migrations.CreateModel( + name='NonSortableNote', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('text', models.CharField(max_length=100)), + ], + ), + migrations.CreateModel( + name='Note', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('text', models.CharField(max_length=100)), + ('order', models.PositiveIntegerField(default=0, editable=False)), + ], + options={ + 'ordering': ['order'], + }, + ), + migrations.CreateModel( + name='Person', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('first_name', models.CharField(max_length=50)), + ('last_name', models.CharField(max_length=50)), + ('is_board_member', models.BooleanField(default=False, verbose_name='Board Member')), + ('order', models.PositiveIntegerField(default=0, editable=False)), + ], + options={ + 'verbose_name_plural': 'People', + 'ordering': ['order'], + }, + ), + migrations.CreateModel( + name='Project', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=50)), + ('description', models.TextField()), + ('order', models.PositiveIntegerField(default=0, editable=False)), + ('category', adminsortable.fields.SortableForeignKey(on_delete=django.db.models.deletion.CASCADE, to='samples.Category')), + ], + options={ + 'ordering': ['order'], + }, + ), + migrations.CreateModel( + name='SortableCategoryWidget', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=50)), + ('order', models.PositiveIntegerField(default=0, editable=False)), + ('non_sortable_category', adminsortable.fields.SortableForeignKey(on_delete=django.db.models.deletion.CASCADE, to='samples.NonSortableCategory')), + ], + options={ + 'verbose_name': 'Sortable Category Widget', + 'verbose_name_plural': 'Sortable Category Widgets', + 'ordering': ['order'], + }, + ), + migrations.CreateModel( + name='SortableNonInlineCategory', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=50)), + ('order', models.PositiveIntegerField(default=0, editable=False)), + ('non_sortable_category', adminsortable.fields.SortableForeignKey(on_delete=django.db.models.deletion.CASCADE, to='samples.NonSortableCategory')), + ], + options={ + 'verbose_name': 'Sortable Non-Inline Category', + 'verbose_name_plural': 'Sortable Non-Inline Categories', + 'ordering': ['order'], + }, + ), + migrations.CreateModel( + name='Widget', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=50)), + ('order', models.PositiveIntegerField(default=0, editable=False)), + ], + options={ + 'ordering': ['order'], + }, + ), + migrations.AddField( + model_name='note', + name='project', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='samples.Project'), + ), + migrations.AddField( + model_name='nonsortablenote', + name='project', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='samples.Project'), + ), + migrations.AddField( + model_name='nonsortablecredit', + name='project', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='samples.Project'), + ), + migrations.AddField( + model_name='credit', + name='project', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='samples.Project'), + ), + migrations.AddField( + model_name='component', + name='widget', + field=adminsortable.fields.SortableForeignKey(on_delete=django.db.models.deletion.CASCADE, to='samples.Widget'), + ), + ] diff --git a/sample_project/samples/migrations/0002_auto_20180319_2117.py b/sample_project/samples/migrations/0002_auto_20180319_2117.py new file mode 100644 index 0000000..0bf0847 --- /dev/null +++ b/sample_project/samples/migrations/0002_auto_20180319_2117.py @@ -0,0 +1,29 @@ +# Generated by Django 2.0 on 2018-03-20 01:17 + +from django.db import migrations, models +import uuid + + +class Migration(migrations.Migration): + + dependencies = [ + ('samples', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='TestNonAutoFieldModel', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('order', models.PositiveIntegerField(db_index=True, editable=False)), + ], + options={ + 'ordering': ['order'], + }, + ), + migrations.AlterField( + model_name='category', + name='order', + field=models.PositiveIntegerField(default=0, editable=False), + ), + ] diff --git a/sample_project/samples/migrations/__init__.py b/sample_project/samples/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sample_project/app/models.py b/sample_project/samples/models.py similarity index 84% rename from sample_project/app/models.py rename to sample_project/samples/models.py index 6f1186f..35b2611 100644 --- a/sample_project/app/models.py +++ b/sample_project/samples/models.py @@ -1,10 +1,6 @@ -from django import VERSION - -if VERSION < (1, 9): - from django.contrib.contenttypes.generic import GenericForeignKey -else: - from django.contrib.contenttypes.fields import GenericForeignKey +import uuid +from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.encoding import python_2_unicode_compatible @@ -30,7 +26,7 @@ class Category(SimpleModel, SortableMixin): verbose_name_plural = 'Categories' ordering = ['order'] - order = models.PositiveIntegerField(default=0) + order = models.PositiveIntegerField(default=0, editable=False) # A model with an override of its queryset for admin @@ -51,7 +47,7 @@ class Project(SimpleModel, SortableMixin): class Meta: ordering = ['order'] - category = SortableForeignKey(Category) + category = SortableForeignKey(Category, on_delete=models.CASCADE) description = models.TextField() order = models.PositiveIntegerField(default=0, editable=False) @@ -63,7 +59,7 @@ class Credit(SortableMixin): class Meta: ordering = ['order'] - project = models.ForeignKey(Project) + project = models.ForeignKey(Project, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, help_text="Given name") last_name = models.CharField(max_length=30, help_text="Family name") @@ -79,7 +75,7 @@ class Note(SortableMixin): class Meta: ordering = ['order'] - project = models.ForeignKey(Project) + project = models.ForeignKey(Project, on_delete=models.CASCADE) text = models.CharField(max_length=100) order = models.PositiveIntegerField(default=0, editable=False) @@ -91,7 +87,7 @@ class Note(SortableMixin): # Registered as a tabular inline on `Project` which can't be sorted @python_2_unicode_compatible class NonSortableCredit(models.Model): - project = models.ForeignKey(Project) + project = models.ForeignKey(Project, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, help_text="Given name") last_name = models.CharField(max_length=30, help_text="Family name") @@ -102,7 +98,7 @@ class NonSortableCredit(models.Model): # Registered as a stacked inline on `Project` which can't be sorted @python_2_unicode_compatible class NonSortableNote(models.Model): - project = models.ForeignKey(Project) + project = models.ForeignKey(Project, on_delete=models.CASCADE) text = models.CharField(max_length=100) def __str__(self): @@ -112,7 +108,7 @@ class NonSortableNote(models.Model): # A generic bound model @python_2_unicode_compatible class GenericNote(SimpleModel, SortableMixin): - content_type = models.ForeignKey(ContentType, + content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, verbose_name=u"Content type", related_name="generic_notes") object_id = models.PositiveIntegerField(u"Content id") content_object = GenericForeignKey(ct_field='content_type', @@ -133,7 +129,7 @@ class Component(SimpleModel, SortableMixin): class Meta: ordering = ['order'] - widget = SortableForeignKey(Widget) + widget = SortableForeignKey(Widget, on_delete=models.CASCADE) order = models.PositiveIntegerField(default=0, editable=False) @@ -183,7 +179,8 @@ class SortableCategoryWidget(SimpleModel, SortableMixin): verbose_name = 'Sortable Category Widget' verbose_name_plural = 'Sortable Category Widgets' - non_sortable_category = SortableForeignKey(NonSortableCategory) + non_sortable_category = SortableForeignKey( + NonSortableCategory, on_delete=models.CASCADE) order = models.PositiveIntegerField(default=0, editable=False) @@ -197,7 +194,8 @@ class SortableNonInlineCategory(SimpleModel, SortableMixin): that is *not* sortable, and is also not defined as an inline of the SortableForeignKey field.""" - non_sortable_category = SortableForeignKey(NonSortableCategory) + non_sortable_category = SortableForeignKey( + NonSortableCategory, on_delete=models.CASCADE) order = models.PositiveIntegerField(default=0, editable=False) @@ -229,7 +227,7 @@ class CustomWidget(SortableMixin, SimpleModel): @python_2_unicode_compatible class CustomWidgetComponent(SortableMixin, SimpleModel): - custom_widget = models.ForeignKey(CustomWidget) + custom_widget = models.ForeignKey(CustomWidget, on_delete=models.CASCADE) # custom field for ordering widget_order = models.PositiveIntegerField(default=0, db_index=True, @@ -253,3 +251,12 @@ class BackwardCompatibleWidget(Sortable, SimpleModel): def __str__(self): return self.title + + +@python_2_unicode_compatible +class TestNonAutoFieldModel(SortableMixin): + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + order = models.PositiveIntegerField(editable=False, db_index=True) + + class Meta: + ordering = ['order'] diff --git a/sample_project/app/tests.py b/sample_project/samples/tests.py similarity index 87% rename from sample_project/app/tests.py rename to sample_project/samples/tests.py index e573ebb..4fb1442 100644 --- a/sample_project/app/tests.py +++ b/sample_project/samples/tests.py @@ -1,16 +1,12 @@ try: - import httplib + import httplib # Python 2 except ImportError: - import http.client as httplib - -from django import VERSION - -if VERSION > (1, 8): - import uuid + import http.client as httplib # Python 3 import json -from django import VERSION +import django + from django.contrib.auth.models import User from django.db import models from django.test import TestCase @@ -18,28 +14,7 @@ from django.test.client import Client from adminsortable.models import SortableMixin from adminsortable.utils import get_is_sortable -from app.models import Category, Person, Project - - -class TestSortableModel(SortableMixin): - title = models.CharField(max_length=100) - - order = models.PositiveIntegerField(default=0, editable=False) - - class Meta: - ordering = ['order'] - - def __unicode__(self): - return self.title - - -if VERSION > (1, 8): - class TestNonAutoFieldModel(SortableMixin): - id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) - order = models.PositiveIntegerField(editable=False, db_index=True) - - class Meta: - ordering = ['order'] +from .models import Category, Person, Project, TestNonAutoFieldModel class SortableTestCase(TestCase): @@ -79,8 +54,12 @@ class SortableTestCase(TestCase): return category def test_new_user_is_authenticated(self): - self.assertEqual(self.user.is_authenticated(), True, - 'User is not authenticated') + if django.VERSION < (1, 10): + self.assertEqual(self.user.is_authenticated(), True, + 'User is not authenticated') + else: + self.assertEqual(self.user.is_authenticated, True, + 'User is not authenticated') def test_new_user_is_staff(self): self.assertEqual(self.user.is_staff, True, 'User is not staff') @@ -113,8 +92,8 @@ class SortableTestCase(TestCase): def test_adminsortable_change_list_view(self): self.client.login(username=self.user.username, password=self.user_raw_password) - response = self.client.get('/admin/app/category/sort/') - self.assertEquals(response.status_code, httplib.OK, + response = self.client.get('/admin/samples/category/sort/') + self.assertEqual(response.status_code, httplib.OK, 'Unable to reach sort view.') def make_test_categories(self): @@ -124,7 +103,7 @@ class SortableTestCase(TestCase): return category1, category2, category3 def get_sorting_url(self, model): - return '/admin/app/project/sort/do-sorting/{0}/'.format( + return '/admin/samples/project/sort/do-sorting/{0}/'.format( model.model_type_id()) def get_category_indexes(self, *categories): @@ -135,7 +114,7 @@ class SortableTestCase(TestCase): password=self.user_raw_password) self.assertTrue(logged_in, 'User is not logged in') - response = self.client.get('/admin/app/category/sort/') + response = self.client.get('/admin/samples/category/sort/') self.assertEqual(response.status_code, httplib.OK, 'Admin sort request failed.') @@ -185,8 +164,7 @@ class SortableTestCase(TestCase): # make a normal POST response = self.client.post(self.get_sorting_url(Category), data=self.get_category_indexes(category1, category2, category3)) - content = json.loads(response.content.decode(encoding='UTF-8'), - 'latin-1') + content = json.loads(response.content.decode(encoding='UTF-8')) self.assertFalse(content.get('objects_sorted'), 'Objects should not have been sorted. An ajax post is required.') @@ -202,8 +180,7 @@ class SortableTestCase(TestCase): response = self.client.post(self.get_sorting_url(Category), data=self.get_category_indexes(category3, category2, category1), HTTP_X_REQUESTED_WITH='XMLHttpRequest') - content = json.loads(response.content.decode(encoding='UTF-8'), - 'latin-1') + content = json.loads(response.content.decode(encoding='UTF-8')) self.assertTrue(content.get('objects_sorted'), 'Objects should have been sorted.') @@ -256,8 +233,8 @@ class SortableTestCase(TestCase): self.client.login(username=self.user.username, password=self.user_raw_password) - response = self.client.get('/admin/app/project/sort/') - self.assertEquals(response.status_code, httplib.OK, + response = self.client.get('/admin/samples/project/sort/') + self.assertEqual(response.status_code, httplib.OK, 'Unable to reach sort view.') def test_adminsortable_change_list_view_permission_denied(self): @@ -266,9 +243,9 @@ class SortableTestCase(TestCase): self.client.login(username=self.staff.username, password=self.staff_raw_password) - response = self.client.get('/admin/app/project/sort/') - self.assertEquals(response.status_code, httplib.FORBIDDEN, - 'Sort view must be forbidden.') + response = self.client.get('/admin/samples/project/sort/') + self.assertEqual(response.status_code, httplib.FORBIDDEN, + 'Sort view must be forbidden.') def test_adminsortable_inline_changelist_success(self): self.client.login(username=self.user.username, @@ -291,8 +268,7 @@ class SortableTestCase(TestCase): response.status_code, httplib.OK, 'Note inline must be sortable in ProjectAdmin') - content = json.loads(response.content.decode(encoding='UTF-8'), - 'latin-1') + content = json.loads(response.content.decode(encoding='UTF-8')) self.assertTrue(content.get('objects_sorted'), 'Objects should have been sorted.') @@ -317,8 +293,5 @@ class SortableTestCase(TestCase): self.assertEqual(notes, expected_notes) def test_save_non_auto_field_model(self): - if VERSION > (1, 8): - model = TestNonAutoFieldModel() - model.save() - else: - pass + model = TestNonAutoFieldModel() + model.save() diff --git a/setup.py b/setup.py index 2f34301..7d075e0 100644 --- a/setup.py +++ b/setup.py @@ -1,7 +1,7 @@ from setuptools import setup, find_packages try: - README = open('README').read() + README = open('README.rst').read() except: README = None diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..b67add1 --- /dev/null +++ b/tox.ini @@ -0,0 +1,37 @@ +[tox] +envlist = django{1.8,1.9,1.10,1.11,2}-{py27,py34,py35,py36},coverage + +[testenv] +deps = + coverage + django1.8: Django>=1.8,<1.9 + django1.9: Django>=1.9,<1.10 + django1.10: Django>=1.10,<1.11 + django1.11: Django>=1.11a1,<1.12 + django2.0: Django>=2.0 +whitelist_externals = cd +setenv = + PYTHONPATH = {toxinidir}/sample_project + PYTHONWARNINGS = module + PYTHONDONTWRITEBYTECODE = 1 +commands = + coverage run -p sample_project/manage.py test app + +[testenv:coverage] +deps = coverage +skip_install = true +commands = + coverage combine + coverage report + coverage html + +[coverage:run] +branch = True +parallel = True +source = + adminsortable + sample_project + +[coverage:report] +exclude_lines = + if __name__ == .__main__.: