Merge branch 'master' into develop

master
Brandon Taylor 2018-03-19 21:40:06 -04:00
commit fa8a5f12a8
36 changed files with 773 additions and 615 deletions

View File

@ -1,8 +1,8 @@
# Django Admin Sortable # Django Admin Sortable
[![Build Status](https://travis-ci.org/iambrandontaylor/django-admin-sortable.svg?branch=master)](https://travis-ci.org/iambrandontaylor/django-admin-sortable) [![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)
Current version: 2.0.21 [![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 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, 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) ![sortable-inlines](http://res.cloudinary.com/alsoicode/image/upload/v1451237555/django-admin-sortable/sortable-inlines.jpg)
## Supported Django Versions ## 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 ### Other notes of interest regarding versions
django-admin-sortable 1.5.2 introduced backward-incompatible changes for Django 1.4.x 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 ## Configuration
1. Add `adminsortable` to your `INSTALLED_APPS`. 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 3. Ensure that `CSRF_COOKIE_HTTPONLY` has not been set to `True`, as
django-admin-sortable is currently incompatible with that setting. 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` - `BigIntegerField`
- `Meta.ordering` **must only contain one value**, otherwise, your objects will not be sorted correctly. - `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. - 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: Sample Model:
@ -411,12 +413,12 @@ These attributes have default values of:
change_list_template_extends = 'admin/change_list.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/stacked-1.10.x.html
templates/adminsortable/edit_inline/tabular-inline-1.5.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/stacked.html
templates/adminsortable/edit_inline/tabular.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 contents of `sortable-stacked-inline-change-form.html` at a minimum need to extend
the extrahead block with: the extrahead block with:
```html ```html+django
{% extends "admin/cms/page/plugin_change_form.html" %} {% extends "admin/cms/page/plugin_change_form.html" %}
{% load static from staticfiles %} {% load static from staticfiles %}
{% block extrahead %} {% block extrahead %}
{{ block.super }} {{ block.super }}
<script type="text/javascript" src="{% static 'adminsortable/js/jquery-ui-django-admin.min.js' %}"></script> <script src="{% static 'adminsortable/js/jquery-ui-django-admin.min.js' %}"></script>
<script type="text/javascript" src="{% static 'adminsortable/js/jquery.django-csrf.js' %}"></script> <script src="{% static 'adminsortable/js/jquery.ui.touch-punch.min.js' %}"></script>
<script type="text/javascript" src="{% static 'adminsortable/js/admin.sortable.stacked.inlines.js' %}"></script> <script src="{% static 'adminsortable/js/jquery.django-csrf.js' %}"></script>
<script src="{% static 'adminsortable/js/admin.sortable.stacked.inlines.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'adminsortable/css/admin.sortable.inline.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'adminsortable/css/admin.sortable.inline.css' %}" />
{% endblock extrahead %} {% 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: 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
<script src="{% static 'adminsortable/js/admin.sortable.stacked.inlines.js' %}"></script> <script src="{% static 'adminsortable/js/admin.sortable.stacked.inlines.js' %}"></script>
``` ```
with: with:
```html ```html+django
<script src="{% static 'adminsortable/js/admin.sortable.tabular.inlines.js' %}"></script> <script src="{% static 'adminsortable/js/admin.sortable.tabular.inlines.js' %}"></script>
``` ```
### 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
<script type="text/javascript" src="{% static 'adminsortable/js/jquery.django-csrf.js' %}"></script>
```
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 ### Rationale
Other projects have added drag-and-drop ordering to the ChangeList Other projects have added drag-and-drop ordering to the ChangeList
view, however this introduces a couple of problems... 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 ### Status
django-admin-sortable is currently used in production. 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](https://github.com/iambrandontaylor/django-admin-sortable/pull/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](https://github.com/mrmachine).
### Future ### 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. - Better template support for foreign keys that are self referential. If someone would like to take on rendering recursive sortables, that would be super.

View File

@ -1,9 +1,7 @@
Django Admin Sortable Django Admin Sortable
===================== =====================
|Build Status| |PyPI version| |Python versions| |Build Status|
Current version: 2.0.21
This project makes it easy to add drag-and-drop ordering to any model in 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, Django admin. Inlines for a sortable model may also be made sortable,
@ -26,9 +24,9 @@ Sorting inlines:
Supported Django Versions 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 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 django-admin-sortable 1.6.6 introduced a backward-incompatible change
for the ``sorting_filters`` attribute. Please convert your attributes to 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 havent already.
django-admin-sortable 1.7.1 and higher are compatible with Python 3. django-admin-sortable 1.7.1 and higher are compatible with Python 3.
@ -47,7 +45,7 @@ Installation
1. ``$ pip install django-admin-sortable`` 1. ``$ pip install django-admin-sortable``
--or-- or
Download django-admin-sortable from Download django-admin-sortable from
`source <https://github.com/iambrandontaylor/django-admin-sortable/archive/master.zip>`__ `source <https://github.com/iambrandontaylor/django-admin-sortable/archive/master.zip>`__
@ -64,8 +62,13 @@ Configuration
------------- -------------
1. Add ``adminsortable`` to your ``INSTALLED_APPS``. 1. Add ``adminsortable`` to your ``INSTALLED_APPS``.
2. Ensure ``django.core.context_processors.static`` is in your 2. Ensure ``django.template.context_processors.static`` is in your
``TEMPLATE_CONTEXT_PROCESSORS``. ``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 3. Ensure that ``CSRF_COOKIE_HTTPONLY`` has not been set to ``True``, as
django-admin-sortable is currently incompatible with that setting. django-admin-sortable is currently incompatible with that setting.
@ -81,11 +84,11 @@ to the location you serve static files from.
Testing 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 login credentials for admin are: admin/admin
When a model is sortable, a tool-area link will be added that says 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. view where you can drag-and-drop the records into order.
Inlines may be drag-and-dropped into any order directly from the change Inlines may be drag-and-dropped into any order directly from the change
@ -97,11 +100,11 @@ Usage
Models 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: and at minimum, define:
- The field which should be used for ``Meta.ordering``, which must - 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 Djangos ORM:
- ``PositiveIntegerField`` - ``PositiveIntegerField``
- ``IntegerField`` - ``IntegerField``
- ``PositiveSmallIntegerField`` - ``PositiveSmallIntegerField``
@ -110,6 +113,9 @@ and at minimum, define:
- ``Meta.ordering`` **must only contain one value**, otherwise, your - ``Meta.ordering`` **must only contain one value**, otherwise, your
objects will not be sorted correctly. 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 - It is recommended that you set ``editable=False`` and
``db_index=True`` on the field defined in ``Meta.ordering`` for a ``db_index=True`` on the field defined in ``Meta.ordering`` for a
seamless Django admin experience and faster lookups on the objects. seamless Django admin experience and faster lookups on the objects.
@ -137,14 +143,14 @@ Sample Model:
def __unicode__(self): def __unicode__(self):
return self.title return self.title
Support for models that don't use an ``AutoField`` for their primary key Support for models that dont use an ``AutoField`` for their primary key
are also supported in version 2.0.20 or higher. are also supported in version 2.0.20 or higher.
Common Use Case Common Use Case
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
A common use case is to have child objects that are sortable relative to 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, heres how you would
set up your models and admin options: set up your models and admin options:
.. code:: python .. code:: python
@ -235,7 +241,7 @@ will be grouped by the non-sortable foreign key when sorting.
Backwards Compatibility Backwards Compatibility
~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~
If you previously used Django Admin Sortable, **DON'T PANIC** - If you previously used Django Admin Sortable, **DONT PANIC** -
everything will still work exactly as before ***without any changes to everything will still work exactly as before ***without any changes to
your code***. Going forward, it is recommended that you use the new your code***. Going forward, it is recommended that you use the new
``SortableMixin`` on your models, as pre-2.0 compatibility might not be ``SortableMixin`` on your models, as pre-2.0 compatibility might not be
@ -283,7 +289,7 @@ following data:
| | Child Model 4 | | | Child Model 4 |
| | Child Model 5 | | | 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`` ``get_previous`` would return ``None``
If you wish to override this behavior, pass in: 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) 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: should you need to:
.. code:: python .. code:: python
@ -306,13 +312,13 @@ Adding Sorting to an existing model
Django 1.5.x to 1.6.x Django 1.5.x to 1.6.x
^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
If you're adding Sorting to an existing model, it is recommended that If youre adding Sorting to an existing model, it is recommended that
you use `django-south <http://south.areacode.com/>`__ to create a schema you use `django-south <http://south.areacode.com/>`__ 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 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 .. code:: python
@ -328,7 +334,7 @@ more information on South Data Migrations.
Django 1.7.x or higher 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 dont have to use
south, but the process of adding and running migrations is nearly south, but the process of adding and running migrations is nearly
identical. Take a look at the identical. Take a look at the
`Migrations <https://docs.djangoproject.com/en/1.7/topics/migrations/>`__ `Migrations <https://docs.djangoproject.com/en/1.7/topics/migrations/>`__
@ -399,8 +405,8 @@ Overriding ``queryset()``
django-admin-sortable supports custom queryset overrides on admin models django-admin-sortable supports custom queryset overrides on admin models
and inline models in Django admin! and inline models in Django admin!
If you're providing an override of a SortableAdmin or Sortable inline If youre providing an override of a SortableAdmin or Sortable inline
model, you don't need to do anything extra. django-admin-sortable will model, you dont need to do anything extra. django-admin-sortable will
automatically honor your queryset. automatically honor your queryset.
Have a look at the WidgetAdmin class in the sample project for an 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 return qs
If you override the queryset of an inline, the number of objects present 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 wont be able to automatically determine
if the inline model is sortable from here, which is why we have to set 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. 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()`` ``.filter()`` on a QuerySet, and is applied *after* ``get_queryset()``
on the admin class, allowing you to override the queryset as you would on the admin class, allowing you to override the queryset as you would
normally in admin but apply additional filters for sorting. The text 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 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 listed. If no ``sorting_filters`` are specified, the text Change
Order" will be displayed for the link. Order will be displayed for the link.
Self-Referential SortableForeignKey Self-Referential SortableForeignKey
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
You can specify a self-referential SortableForeignKey field, however the You can specify a self-referential SortableForeignKey field, however the
admin interface will currently show a model that is a grandchild at 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. Im working to resolve this issue.
Important! Important!
'''''''''' ''''''''''
django-admin-sortable 1.6.6 introduced a backwards-incompatible change django-admin-sortable 1.6.6 introduced a backwards-incompatible change
for ``sorting_filters``. Previously this attribute was defined as a 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 youll need to change your values over to the new
tuple-based format. tuple-based format.
An example of sorting subsets would be a "Board of Directors". In this 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 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 on the Board of Directors and some not, and you need to sort them
independently. independently.
@ -493,9 +499,9 @@ independently.
Extending custom templates Extending custom templates
^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^
By default, adminsortable's change form and change list views inherit By default, adminsortables change form and change list views inherit
from Django admin's standard templates. Sometimes you need to have a from Django admins standard templates. Sometimes you need to have a
custom change form or change list, but also need adminsortable's CSS and custom change form or change list, but also need adminsortables CSS and
JavaScript for inline models that are sortable for example. JavaScript for inline models that are sortable for example.
SortableAdmin has two attributes you can override for this use case: SortableAdmin has two attributes you can override for this use case:
@ -512,24 +518,24 @@ These attributes have default values of:
change_form_template_extends = 'admin/change_form.html' change_form_template_extends = 'admin/change_form.html'
change_list_template_extends = 'admin/change_list.html' change_list_template_extends = 'admin/change_list.html'
If you need to extend the inline change form templates, you'll need to If you need to extend the inline change form templates, youll need to
select the right one, depending on your version of Django. For Django select the right one, depending on your version of Django. For 1.10.x or
1.5.x or below, you'll need to extend one of the following: below, youll need to extend one of the following:
:: ::
templates/adminsortable/edit_inline/stacked-1.5.x.html templates/adminsortable/edit_inline/stacked-1.10.x.html
templates/adminsortable/edit_inline/tabular-inline-1.5.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/stacked.html
templates/adminsortable/edit_inline/tabular.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 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 make them difficult to sort. If you anticipate the height of a stacked
@ -539,7 +545,7 @@ SortableTabularInline instead.
Django-CMS integration 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 wont
automatically include the necessary JavaScript for django-admin-sortable automatically include the necessary JavaScript for django-admin-sortable
to work. Fortunately, this is easy to resolve, as the ``CMSPlugin`` to work. Fortunately, this is easy to resolve, as the ``CMSPlugin``
class allows a change form template to be specified: 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 The contents of ``sortable-stacked-inline-change-form.html`` at a
minimum need to extend the extrahead block with: minimum need to extend the extrahead block with:
.. code:: html .. code:: html+django
{% extends "admin/cms/page/plugin_change_form.html" %} {% extends "admin/cms/page/plugin_change_form.html" %}
{% load static from staticfiles %} {% load static from staticfiles %}
{% block extrahead %} {% block extrahead %}
{{ block.super }} {{ block.super }}
<script type="text/javascript" src="{% static 'adminsortable/js/jquery-ui-django-admin.min.js' %}"></script> <script src="{% static 'adminsortable/js/jquery-ui-django-admin.min.js' %}"></script>
<script type="text/javascript" src="{% static 'adminsortable/js/jquery.django-csrf.js' %}"></script> <script src="{% static 'adminsortable/js/jquery.ui.touch-punch.min.js' %}"></script>
<script type="text/javascript" src="{% static 'adminsortable/js/admin.sortable.stacked.inlines.js' %}"></script> <script src="{% static 'adminsortable/js/jquery.django-csrf.js' %}"></script>
<script src="{% static 'adminsortable/js/admin.sortable.stacked.inlines.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'adminsortable/css/admin.sortable.inline.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'adminsortable/css/admin.sortable.inline.css' %}" />
{% endblock extrahead %} {% 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 plugin as Django-CMS already includes sorting for plugin instances. For
tabular inlines, just substitute: tabular inlines, just substitute:
.. code:: html .. code:: html+django
<script src="{% static 'adminsortable/js/admin.sortable.stacked.inlines.js' %}"></script> <script src="{% static 'adminsortable/js/admin.sortable.stacked.inlines.js' %}"></script>
with: with:
.. code:: html .. code:: html+django
<script src="{% static 'adminsortable/js/admin.sortable.tabular.inlines.js' %}"></script> <script src="{% static 'adminsortable/js/admin.sortable.tabular.inlines.js' %}"></script>
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
<script type="text/javascript" src="{% static 'adminsortable/js/jquery.django-csrf.js' %}"></script>
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 Rationale
~~~~~~~~~ ~~~~~~~~~
Other projects have added drag-and-drop ordering to the ChangeList view, 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 - The ChangeList view supports pagination, which makes drag-and-drop
ordering across pages impossible. ordering across pages impossible.
@ -617,13 +657,11 @@ Status
django-admin-sortable is currently used in production. django-admin-sortable is currently used in production.
What's new in 2.0.21? Whats new in 2.1.4?
~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~
- Fixed a regression introduced by `Pull Request - Improved performance on large data sets. Credit to
143 <https://github.com/iambrandontaylor/django-admin-sortable/pull/143>`__ `mrmachine <https://github.com/mrmachine>`__.
which caused models sortable by a foriegn key to not persist the sort
order correctly.
Future Future
~~~~~~ ~~~~~~
@ -637,5 +675,9 @@ License
django-admin-sortable is released under the Apache Public License v2. 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 .. |PyPI version| image:: https://img.shields.io/pypi/v/django-admin-sortable.svg
:target: https://travis-ci.org/iambrandontaylor/django-admin-sortable :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

View File

@ -1,4 +1,4 @@
VERSION = (2, 0, 21) VERSION = (2, 1, 4)
DEV_N = None DEV_N = None

View File

@ -3,24 +3,11 @@ import json
from django import VERSION from django import VERSION
from django.conf import settings from django.conf import settings
try:
from django.conf.urls import url from django.conf.urls import url
except ImportError:
# Django < 1.4
from django.conf.urls.defaults import url
from django.contrib.admin import ModelAdmin, TabularInline, StackedInline from django.contrib.admin import ModelAdmin, TabularInline, StackedInline
from django.contrib.admin.options import InlineModelAdmin from django.contrib.admin.options import InlineModelAdmin
try:
from django.contrib.contenttypes.admin import (GenericStackedInline, from django.contrib.contenttypes.admin import (GenericStackedInline,
GenericTabularInline) GenericTabularInline)
except:
# Django < 1.7
from django.contrib.contenttypes.generic import (GenericStackedInline,
GenericTabularInline)
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied from django.core.exceptions import PermissionDenied
from django.http import HttpResponse, Http404 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 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. object_tools block to take people to the view to change the sorting.
""" """
if get_is_sortable(self.get_queryset(request)):
try:
qs_method = getattr(self, 'get_queryset', self.queryset)
except AttributeError:
qs_method = self.get_queryset
if get_is_sortable(qs_method(request)):
self.change_list_template = \ self.change_list_template = \
self.sortable_change_list_with_sort_link_template self.sortable_change_list_with_sort_link_template
self.is_sortable = True self.is_sortable = True
@ -101,12 +82,7 @@ class SortableAdmin(SortableAdminBase, ModelAdmin):
def get_urls(self): def get_urls(self):
urls = super(SortableAdmin, self).get_urls() urls = super(SortableAdmin, self).get_urls()
opts = self.model._meta info = self.model._meta.app_label, self.model._meta.model_name
try:
info = opts.app_label, opts.model_name
except AttributeError:
# Django < 1.7
info = opts.app_label, opts.model_name
# this ajax view changes the order of instances of the model type # this ajax view changes the order of instances of the model type
admin_do_sorting_url = url( admin_do_sorting_url = url(
@ -126,6 +102,24 @@ class SortableAdmin(SortableAdminBase, ModelAdmin):
] + urls ] + urls
return 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): def sort_view(self, request):
""" """
Custom admin view that displays the objects as a list whose sort 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) \ jquery_lib_path = 'admin/js/jquery.js' if VERSION < (1, 9) \
else 'admin/js/vendor/jquery/jquery.js' 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 # Determine if we need to regroup objects relative to a
# foreign key specified on the model class that is extending Sortable. # foreign key specified on the model class that is extending Sortable.
# Legacy support for 'sortable_by' defined as a model property # Legacy support for 'sortable_by' defined as a model property
@ -169,6 +146,10 @@ class SortableAdmin(SortableAdminBase, ModelAdmin):
for field in self.model._meta.fields: for field in self.model._meta.fields:
if isinstance(field, SortableForeignKey): if isinstance(field, SortableForeignKey):
try:
sortable_by_fk = field.remote_field.model
except AttributeError:
# Django < 1.9
sortable_by_fk = field.rel.to sortable_by_fk = field.rel.to
sortable_by_field_name = field.name.lower() sortable_by_field_name = field.name.lower()
sortable_by_class_is_sortable = sortable_by_fk.objects.count() >= 2 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_display_name = \
sortable_by_class_is_sortable = None sortable_by_class_is_sortable = None
objects = self.get_sort_view_queryset(request, sortable_by_expression)
if sortable_by_property or sortable_by_fk: if sortable_by_property or sortable_by_fk:
# Order the objects by the property they are sortable by, # Order the objects by the property they are sortable by,
# then by the order, otherwise the regroup # then by the order, otherwise the regroup
@ -206,9 +189,6 @@ class SortableAdmin(SortableAdminBase, ModelAdmin):
try: try:
order_field_name = opts.model._meta.ordering[0] 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): except (AttributeError, IndexError):
order_field_name = 'order' order_field_name = 'order'
@ -301,8 +281,11 @@ class SortableAdmin(SortableAdminBase, ModelAdmin):
for index in indexes: for index in indexes:
obj = objects_dict.get(index) obj = objects_dict.get(index)
# 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) setattr(obj, order_field_name, start_index)
obj.save() # only update the object's order field
obj.save(update_fields=(order_field_name,))
start_index += step start_index += step
response = {'objects_sorted': True} response = {'objects_sorted': True}
except (KeyError, IndexError, klass.DoesNotExist, except (KeyError, IndexError, klass.DoesNotExist,
@ -329,27 +312,18 @@ class SortableInlineBase(SortableAdminBase, InlineModelAdmin):
' (or Sortable for legacy implementations)') ' (or Sortable for legacy implementations)')
def get_queryset(self, request): 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): if get_is_sortable(qs):
self.model.is_sortable = True self.model.is_sortable = True
else: else:
self.model.is_sortable = False self.model.is_sortable = False
return qs return qs
if VERSION < (1, 6):
queryset = get_queryset
class SortableTabularInline(TabularInline, SortableInlineBase): class SortableTabularInline(TabularInline, SortableInlineBase):
"""Custom template that enables sorting for tabular inlines""" """Custom template that enables sorting for tabular inlines"""
if VERSION >= (1, 10): if VERSION >= (1, 10):
template = 'adminsortable/edit_inline/tabular-1.10.x.html' template = 'adminsortable/edit_inline/tabular-1.10.x.html'
elif VERSION < (1, 6):
template = 'adminsortable/edit_inline/tabular-1.5.x.html'
else: else:
template = 'adminsortable/edit_inline/tabular.html' template = 'adminsortable/edit_inline/tabular.html'
@ -358,8 +332,6 @@ class SortableStackedInline(StackedInline, SortableInlineBase):
"""Custom template that enables sorting for stacked inlines""" """Custom template that enables sorting for stacked inlines"""
if VERSION >= (1, 10): if VERSION >= (1, 10):
template = 'adminsortable/edit_inline/stacked-1.10.x.html' template = 'adminsortable/edit_inline/stacked-1.10.x.html'
elif VERSION < (1, 6):
template = 'adminsortable/edit_inline/stacked-1.5.x.html'
else: else:
template = 'adminsortable/edit_inline/stacked.html' template = 'adminsortable/edit_inline/stacked.html'
@ -368,8 +340,6 @@ class SortableGenericTabularInline(GenericTabularInline, SortableInlineBase):
"""Custom template that enables sorting for tabular inlines""" """Custom template that enables sorting for tabular inlines"""
if VERSION >= (1, 10): if VERSION >= (1, 10):
template = 'adminsortable/edit_inline/tabular-1.10.x.html' template = 'adminsortable/edit_inline/tabular-1.10.x.html'
elif VERSION < (1, 6):
template = 'adminsortable/edit_inline/tabular-1.5.x.html'
else: else:
template = 'adminsortable/edit_inline/tabular.html' template = 'adminsortable/edit_inline/tabular.html'
@ -378,7 +348,5 @@ class SortableGenericStackedInline(GenericStackedInline, SortableInlineBase):
"""Custom template that enables sorting for stacked inlines""" """Custom template that enables sorting for stacked inlines"""
if VERSION >= (1, 10): if VERSION >= (1, 10):
template = 'adminsortable/edit_inline/stacked-1.10.x.html' template = 'adminsortable/edit_inline/stacked-1.10.x.html'
elif VERSION < (1, 6):
template = 'adminsortable/edit_inline/stacked-1.5.x.html'
else: else:
template = 'adminsortable/edit_inline/stacked.html' template = 'adminsortable/edit_inline/stacked.html'

View File

@ -7,14 +7,4 @@ class SortableForeignKey(ForeignKey):
This field replaces previous functionality where `sortable_by` was This field replaces previous functionality where `sortable_by` was
defined as a model property that specified another model class. 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

View File

@ -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 <pb@sungis.lv>\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"

Binary file not shown.

View File

@ -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 <simenheg@gmail.com>\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"

View File

@ -19,10 +19,15 @@
#sortable ul li #sortable ul li
{ {
overflow: auto; overflow: auto;
margin-bottom: 8px;
margin-left: 0; margin-left: 0;
display: block; display: block;
} }
#sortable ul li:last-child {
margin-bottom: 0;
}
#sortable .sortable #sortable .sortable
{ {
list-style: none; list-style: none;

View File

@ -0,0 +1,11 @@
/*!
* jQuery UI Touch Punch 0.2.3
*
* Copyright 20112014, 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);

View File

@ -8,6 +8,7 @@
{% if has_sortable_tabular_inlines or has_sortable_stacked_inlines %} {% if has_sortable_tabular_inlines or has_sortable_stacked_inlines %}
<script type="text/javascript" src="{% static 'adminsortable/js/jquery-ui-django-admin.min.js' %}"></script> <script type="text/javascript" src="{% static 'adminsortable/js/jquery-ui-django-admin.min.js' %}"></script>
<script src="{% static 'adminsortable/js/jquery.ui.touch-punch.min.js' %}"></script>
{% include 'adminsortable/csrf/jquery.django-csrf.html' with csrf_cookie_name=csrf_cookie_name %} {% include 'adminsortable/csrf/jquery.django-csrf.html' with csrf_cookie_name=csrf_cookie_name %}
{% endif %} {% endif %}

View File

@ -1,5 +1,5 @@
{% extends "admin/base_site.html" %} {% extends "admin/base_site.html" %}
{% load i18n admin_urls static admin_list adminsortable_tags %} {% load i18n admin_urls static admin_list %}
{% block extrastyle %} {% block extrastyle %}
{{ block.super }} {{ block.super }}
@ -26,6 +26,7 @@
<script src="{% static jquery_lib_path %}"></script> <script src="{% static jquery_lib_path %}"></script>
<script src="{% static 'admin/js/jquery.init.js' %}"></script> <script src="{% static 'admin/js/jquery.init.js' %}"></script>
<script src="{% static 'adminsortable/js/jquery-ui-django-admin.min.js' %}"></script> <script src="{% static 'adminsortable/js/jquery-ui-django-admin.min.js' %}"></script>
<script src="{% static 'adminsortable/js/jquery.ui.touch-punch.min.js' %}"></script>
{% include 'adminsortable/csrf/jquery.django-csrf.html' with csrf_cookie_name=csrf_cookie_name %} {% include 'adminsortable/csrf/jquery.django-csrf.html' with csrf_cookie_name=csrf_cookie_name %}
<script src="{% static 'adminsortable/js/admin.sortable.js' %}"></script> <script src="{% static 'adminsortable/js/admin.sortable.js' %}"></script>
{% endblock %} {% endblock %}
@ -85,9 +86,9 @@
{% if objects %} {% if objects %}
<div id="sortable"> <div id="sortable">
{% if group_expression %} {% if group_expression %}
{% render_nested_sortable_objects objects group_expression %} {% include "adminsortable/shared/nested_objects.html" %}
{% else %} {% else %}
{% render_sortable_objects objects %} {% include "adminsortable/shared/objects.html" %}
{% endif %} {% endif %}
{% csrf_token %} {% csrf_token %}
</div> </div>

View File

@ -16,7 +16,7 @@
return cookieValue; return cookieValue;
} }
var csrftoken = getCookie('{{ csrf_cookie_name }}'); var csrftoken = '{{ csrf_token }}' || getCookie('{{ csrf_cookie_name }}');
function csrfSafeMethod(method) { function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection // these HTTP methods do not require CSRF protection

View File

@ -1,92 +0,0 @@
{% load i18n admin_modify adminsortable_tags admin_urls %}
{% load static from staticfiles %}
<div class="inline-group" id="{{ inline_admin_formset.formset.prefix }}-group">
<h2>{{ 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 %}</h2>
{{ inline_admin_formset.formset.management_form }}
{{ inline_admin_formset.formset.non_form_errors }}
{% for inline_admin_form in inline_admin_formset %}<div class="inline-related{% if inline_admin_form.original %} has_original{% endif %}{% if forloop.last %} empty-form last-related{% endif %}" id="{{ inline_admin_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}">
<h3>
{% if inline_admin_form.original %}
{% with initial_forms_count=inline_admin_formset.formset.management_form.INITIAL_FORMS.value %}
<i class="fa fa-{% if forloop.first %}sort-desc{% elif forloop.counter == initial_forms_count %}sort-asc{% else %}sort{% endif %}"></i>
{% endwith %}
{% endif %}
<b>{{ inline_admin_formset.opts.verbose_name|title }}:</b>&nbsp;<span class="inline_label">{% if inline_admin_form.original %}{{ inline_admin_form.original }}{% else %}#{{ forloop.counter }}{% endif %}</span>
{% if inline_admin_form.show_url %}<a href="../../../r/{{ inline_admin_form.original_content_type_id }}/{{ inline_admin_form.original.id }}/">{% trans "View on site" %}</a>{% endif %}
{% if inline_admin_formset.formset.can_delete and inline_admin_form.original %}<span class="delete">{{ inline_admin_form.deletion_field.field }} {{ inline_admin_form.deletion_field.label_tag }}</span>{% endif %}
</h3>
{% 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 %}
<input type="hidden" name="admin_sorting_url" value="{% url opts|admin_urlname:'do_sorting' inline_admin_form.original.model_type_id %}" />
{% endif %}
</div>{% endfor %}
</div>
<script type="text/javascript">
(function($) {
$(document).ready(function() {
var rows = "#{{ inline_admin_formset.formset.prefix }}-group .inline-related";
var updateInlineLabel = function(row) {
$(rows).find(".inline_label").each(function(i) {
var count = i + 1;
$(this).html($(this).html().replace(/(#\d+)/g, "#" + count));
});
}
var reinitDateTimeShortCuts = function() {
// Reinitialize the calendar and clock widgets by force, yuck.
if (typeof DateTimeShortcuts != "undefined") {
$(".datetimeshortcuts").remove();
DateTimeShortcuts.init();
}
}
var updateSelectFilter = function() {
// If any SelectFilter widgets were added, instantiate a new instance.
if (typeof SelectFilter != "undefined"){
$(".selectfilter").each(function(index, value){
var namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length-1], false, "{% static 'admin/' %}");
});
$(".selectfilterstacked").each(function(index, value){
var namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length-1], true, "{% static 'admin/' %}");
});
}
}
var initPrepopulatedFields = function(row) {
row.find('.prepopulated_field').each(function() {
var field = $(this);
var input = field.find('input, select, textarea');
var dependency_list = input.data('dependency_list') || [];
var dependencies = [];
$.each(dependency_list, function(i, field_name) {
dependencies.push('#' + row.find(field_name).find('input, select, textarea').attr('id'));
});
if (dependencies.length) {
input.prepopulate(dependencies, input.attr('maxlength'));
}
});
}
$(rows).formset({
prefix: "{{ inline_admin_formset.formset.prefix }}",
addText: "{% blocktrans with inline_admin_formset.opts.verbose_name|title as verbose_name %}Add another {{ verbose_name }}{% endblocktrans %}",
formCssClass: "dynamic-{{ inline_admin_formset.formset.prefix }}",
deleteCssClass: "inline-deletelink",
deleteText: "{% trans "Remove" %}",
emptyCssClass: "empty-form",
removed: updateInlineLabel,
added: (function(row) {
initPrepopulatedFields(row);
reinitDateTimeShortCuts();
updateSelectFilter();
updateInlineLabel(row);
})
});
});
})(django.jQuery);
</script>

View File

@ -1,136 +0,0 @@
{% load i18n admin_modify adminsortable_tags admin_urls %}
{% load static from staticfiles %}
<div class="inline-group" id="{{ inline_admin_formset.formset.prefix }}-group">
<div class="tabular inline-related {% if forloop.last %}last-related{% endif %}">
{{ inline_admin_formset.formset.management_form }}
<fieldset class="module">
<h2>{{ inline_admin_formset.opts.verbose_name_plural|capfirst }} {% if inline_admin_formset.formset.initial_form_count > 1 %} - {% trans "drag and drop to change order" %}{% endif %}</h2>
{{ inline_admin_formset.formset.non_form_errors }}
<table>
<thead><tr>
{% for field in inline_admin_formset.fields %}
{% if not field.widget.is_hidden %}
<th{% if forloop.first %} colspan="2"{% endif %}{% if field.required %} class="required"{% endif %}>{{ field.label|capfirst }}</th>
{% endif %}
{% endfor %}
{% if inline_admin_formset.formset.can_delete %}<th>{% trans "Delete?" %}</th>{% endif %}
</tr></thead>
<tbody>
{% for inline_admin_form in inline_admin_formset %}
{% if inline_admin_form.form.non_field_errors %}
<tr><td colspan="{{ inline_admin_form|cell_count }}">{{ inline_admin_form.form.non_field_errors }}</td></tr>
{% endif %}
<tr class="{% cycle "row1" "row2" %} {% if inline_admin_form.original or inline_admin_form.show_url %}has_original{% endif %}{% if forloop.last %} empty-form{% endif %}"
id="{{ inline_admin_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}">
<td class="original">
{% if inline_admin_form.original or inline_admin_form.show_url %}<p>
{% with initial_forms_count=inline_admin_form.formset.management_form.INITIAL_FORMS.value %}
<i class="fa fa-{% if forloop.first %}sort-desc{% elif forloop.counter == initial_forms_count %}sort-asc{% else %}sort{% endif %}"></i>
{% endwith %}
{% if inline_admin_form.original %} {{ inline_admin_form.original }}{% endif %}
{% if inline_admin_form.show_url %}<a href="../../../r/{{ inline_admin_form.original_content_type_id }}/{{ inline_admin_form.original.id }}/">{% trans "View on site" %}</a>{% endif %}
</p>{% endif %}
{% if inline_admin_form.has_auto_field %}{{ inline_admin_form.pk_field.field }}{% endif %}
{{ inline_admin_form.fk_field.field }}
{% spaceless %}
{% for fieldset in inline_admin_form %}
{% for line in fieldset %}
{% for field in line %}
{% if field.is_hidden %} {{ field.field }} {% endif %}
{% endfor %}
{% endfor %}
{% endfor %}
{% endspaceless %}
{% if inline_admin_form.original %}
<input type="hidden" name="admin_sorting_url" value="{% url opts|admin_urlname:'do_sorting' inline_admin_form.original.model_type_id %}" />
{% endif %}
</td>
{% for fieldset in inline_admin_form %}
{% for line in fieldset %}
{% for field in line %}
<td class="{{ field.field.name }}">
{% if field.is_readonly %}
<p>{{ field.contents }}</p>
{% else %}
{{ field.field.errors.as_ul }}
{{ field.field }}
{% endif %}
</td>
{% endfor %}
{% endfor %}
{% endfor %}
{% if inline_admin_formset.formset.can_delete %}
<td class="delete">{% if inline_admin_form.original %}{{ inline_admin_form.deletion_field.field }}{% endif %}</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</fieldset>
</div>
</div>
<script type="text/javascript">
(function($) {
$(document).ready(function($) {
var rows = "#{{ inline_admin_formset.formset.prefix }}-group .tabular.inline-related tbody tr";
var alternatingRows = function(row) {
$(rows).not(".add-row").removeClass("row1 row2")
.filter(":even").addClass("row1").end()
.filter(rows + ":odd").addClass("row2");
}
var reinitDateTimeShortCuts = function() {
// Reinitialize the calendar and clock widgets by force
if (typeof DateTimeShortcuts != "undefined") {
$(".datetimeshortcuts").remove();
DateTimeShortcuts.init();
}
}
var updateSelectFilter = function() {
// If any SelectFilter widgets are a part of the new form,
// instantiate a new SelectFilter instance for it.
if (typeof SelectFilter != "undefined"){
$(".selectfilter").each(function(index, value){
var namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length-1], false, "{% static 'admin/' %}");
});
$(".selectfilterstacked").each(function(index, value){
var namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length-1], true, "{% static 'admin/' %}");
});
}
}
var initPrepopulatedFields = function(row) {
row.find('.prepopulated_field').each(function() {
var field = $(this);
var input = field.find('input, select, textarea');
var dependency_list = input.data('dependency_list') || [];
var dependencies = [];
$.each(dependency_list, function(i, field_name) {
dependencies.push('#' + row.find(field_name).find('input, select, textarea').attr('id'));
});
if (dependencies.length) {
input.prepopulate(dependencies, input.attr('maxlength'));
}
});
}
$(rows).formset({
prefix: "{{ inline_admin_formset.formset.prefix }}",
addText: "{% blocktrans with inline_admin_formset.opts.verbose_name|title as verbose_name %}Add another {{ verbose_name }}{% endblocktrans %}",
formCssClass: "dynamic-{{ inline_admin_formset.formset.prefix }}",
deleteCssClass: "inline-deletelink",
deleteText: "{% trans "Remove" %}",
emptyCssClass: "empty-form",
removed: alternatingRows,
added: (function(row) {
initPrepopulatedFields(row);
reinitDateTimeShortCuts();
updateSelectFilter();
alternatingRows(row);
})
});
});
})(django.jQuery);
</script>

View File

@ -1,9 +1,8 @@
{% load adminsortable_tags %}
{% with list_objects_length=list_objects|length %} {% with list_objects_length=list_objects|length %}
{% for object in list_objects %} {% for object in list_objects %}
<li> <li>
{% if list_objects_length > 1 %} {% if list_objects_length > 1 %}
{% render_object_rep object forloop %} {% include "adminsortable/shared/object_rep.html" %}
{% else %} {% else %}
{{ object }} {{ object }}
{% endif %} {% endif %}

View File

@ -1,4 +1,4 @@
{% load django_template_additions adminsortable_tags %} {% load django_template_additions %}
{% dynamic_regroup objects by group_expression as regrouped_objects %} {% dynamic_regroup objects by group_expression as regrouped_objects %}
{% if regrouped_objects %} {% if regrouped_objects %}
<ul {% if sortable_by_class_is_sortable %}class="sortable"{% endif %}> <ul {% if sortable_by_class_is_sortable %}class="sortable"{% endif %}>
@ -6,7 +6,7 @@
{% with object=regrouped_object.grouper %} {% with object=regrouped_object.grouper %}
{% if object %} {% if object %}
<li class="parent">{% if sortable_by_class_is_sortable %} <li class="parent">{% if sortable_by_class_is_sortable %}
{% render_object_rep object forloop %} {% include "adminsortable/shared/object_rep.html" %}
{% else %} {% else %}
{{ object }} {{ object }}
{% endif %} {% endif %}
@ -14,7 +14,7 @@
{% if regrouped_object.list %} {% if regrouped_object.list %}
{% with regrouped_object_list_length=regrouped_object.list|length %} {% with regrouped_object_list_length=regrouped_object.list|length %}
<ul {% if regrouped_object_list_length > 1 %}class="sortable"{% endif %}> <ul {% if 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 %}
</ul> </ul>
{% endwith %} {% endwith %}
{% endif %} {% endif %}

View File

@ -1,4 +1,4 @@
{% load adminsortable_tags admin_urls %} {% load admin_urls %}
<form> <form>
<input name="pk" type="hidden" value="{{ object.pk }}" /> <input name="pk" type="hidden" value="{{ object.pk }}" />

View File

@ -1,7 +1,5 @@
{% load adminsortable_tags %}
{% if objects %} {% if objects %}
<ul class="sortable single"> <ul class="sortable single">
{% render_list_items objects %} {% include "adminsortable/shared/list_items.html" with list_objects=objects %}
</ul> </ul>
{% endif %} {% endif %}

View File

@ -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)

View File

@ -2,11 +2,6 @@ from itertools import groupby
import django import django
from django import template 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() register = template.Library()
@ -64,14 +59,15 @@ def dynamic_regroup(parser, token):
""" """
firstbits = token.contents.split(None, 3) firstbits = token.contents.split(None, 3)
if len(firstbits) != 4: 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]) target = parser.compile_filter(firstbits[1])
if firstbits[2] != 'by': 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) lastbits_reversed = firstbits[3][::-1].split(None, 2)
if lastbits_reversed[1][::-1] != 'as': if lastbits_reversed[1][::-1] != 'as':
raise TemplateSyntaxError("next-to-last argument to 'regroup' tag must" raise template.TemplateSyntaxError(
" be 'as'") "next-to-last argument to 'regroup' tag must be 'as'")
expression = lastbits_reversed[2][::-1] expression = lastbits_reversed[2][::-1]
var_name = lastbits_reversed[0][::-1] var_name = lastbits_reversed[0][::-1]
@ -80,7 +76,7 @@ def dynamic_regroup(parser, token):
return DynamicRegroupNode(target, parser, expression, var_name) return DynamicRegroupNode(target, parser, expression, var_name)
@register.assignment_tag @register.simple_tag
def get_django_version(): def get_django_version():
version = django.VERSION version = django.VERSION
return {'major': version[0], 'minor': version[1]} return {'major': version[0], 'minor': version[1]}

View File

@ -1,6 +1,8 @@
# Django settings for test_project project. # Django settings for test_project project.
import os import os
import django
def map_path(directory_name): def map_path(directory_name):
return os.path.join(os.path.dirname(__file__), return os.path.join(os.path.dirname(__file__),
@ -8,7 +10,6 @@ def map_path(directory_name):
DEBUG = True DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = ( ADMINS = (
# ('Your Name', 'your_email@example.com'), # ('Your Name', 'your_email@example.com'),
@ -91,44 +92,36 @@ STATICFILES_FINDERS = (
# Make this unique, and don't share it with anybody. # 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' 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. MIDDLEWARE = [
TEMPLATE_LOADERS = ( 'django.middleware.security.SecurityMiddleware',
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',
) ]
if django.VERSION < (1, 10):
MIDDLEWARE_CLASSES = MIDDLEWARE
ROOT_URLCONF = 'sample_project.urls' ROOT_URLCONF = 'sample_project.urls'
# Python dotted path to the WSGI application used by Django's runserver. # Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'sample_project.wsgi.application' WSGI_APPLICATION = 'sample_project.wsgi.application'
TEMPLATE_DIRS = (
map_path('templates'),
)
TEMPLATES = [ TEMPLATES = [
{ {
'BACKEND': 'django.template.backends.django.DjangoTemplates', 'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': TEMPLATE_DIRS, 'DIRS': [
map_path('templates'),
],
'APP_DIRS': True, 'APP_DIRS': True,
'OPTIONS': { 'OPTIONS': {
'context_processors': [ 'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug', 'django.template.context_processors.debug',
'django.template.context_processors.i18n', 'django.template.context_processors.request',
'django.template.context_processors.media', 'django.contrib.auth.context_processors.auth',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages', 'django.contrib.messages.context_processors.messages',
], ],
}, },
@ -146,7 +139,7 @@ INSTALLED_APPS = (
'django.contrib.admindocs', 'django.contrib.admindocs',
'adminsortable', 'adminsortable',
'app', 'samples',
) )
# A sample logging configuration. The only tangible logging # 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',
},
]

View File

@ -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 from django.contrib import admin
admin.autodiscover() from django.urls import path
urlpatterns = [ urlpatterns = [
# Examples: path('admin/', admin.site.urls),
# 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)),
] ]

View File

@ -1,6 +0,0 @@
import os
def map_path(directory_name):
return os.path.join(os.path.dirname(__file__),
'../' + directory_name).replace('\\', '/')

View File

@ -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 It exposes the WSGI callable as a module-level variable named ``application``.
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.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
""" """
import os 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 from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_project.settings")
application = get_wsgi_application() application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)

View File

@ -4,7 +4,7 @@ from adminsortable.admin import (SortableAdmin, SortableTabularInline,
SortableStackedInline, SortableGenericStackedInline, SortableStackedInline, SortableGenericStackedInline,
NonSortableParentAdmin) NonSortableParentAdmin)
from adminsortable.utils import get_is_sortable 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, Component, Person, NonSortableCategory, SortableCategoryWidget,
SortableNonInlineCategory, NonSortableCredit, NonSortableNote, SortableNonInlineCategory, NonSortableCredit, NonSortableNote,
CustomWidget, CustomWidgetComponent, BackwardCompatibleWidget) CustomWidget, CustomWidgetComponent, BackwardCompatibleWidget)
@ -26,8 +26,8 @@ class ComponentInline(SortableStackedInline):
# ) # )
model = Component model = Component
def queryset(self, request): def get_queryset(self, request):
qs = super(ComponentInline, self).queryset( qs = super(ComponentInline, self).get_queryset(
request).exclude(title__icontains='2') request).exclude(title__icontains='2')
if get_is_sortable(qs): if get_is_sortable(qs):
self.model.is_sortable = True self.model.is_sortable = True
@ -37,14 +37,14 @@ class ComponentInline(SortableStackedInline):
class WidgetAdmin(SortableAdmin): class WidgetAdmin(SortableAdmin):
def queryset(self, request): def get_queryset(self, request):
""" """
A simple example demonstrating that adminsortable works even in A simple example demonstrating that adminsortable works even in
situations where you need to filter the queryset in admin. Here, situations where you need to filter the queryset in admin. Here,
we are just filtering out `widget` instances with an pk higher we are just filtering out `widget` instances with an pk higher
than 3 than 3
""" """
qs = super(WidgetAdmin, self).queryset(request) qs = super(WidgetAdmin, self).get_queryset(request)
return qs.filter(id__lte=3) return qs.filter(id__lte=3)
inlines = [ComponentInline] inlines = [ComponentInline]

View File

@ -0,0 +1,5 @@
from django.apps import AppConfig
class SamplesConfig(AppConfig):
name = 'samples'

View File

@ -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'),
),
]

View File

@ -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),
),
]

View File

@ -1,10 +1,6 @@
from django import VERSION import uuid
if VERSION < (1, 9):
from django.contrib.contenttypes.generic import GenericForeignKey
else:
from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.db import models from django.db import models
from django.utils.encoding import python_2_unicode_compatible from django.utils.encoding import python_2_unicode_compatible
@ -30,7 +26,7 @@ class Category(SimpleModel, SortableMixin):
verbose_name_plural = 'Categories' verbose_name_plural = 'Categories'
ordering = ['order'] ordering = ['order']
order = models.PositiveIntegerField(default=0) order = models.PositiveIntegerField(default=0, editable=False)
# A model with an override of its queryset for admin # A model with an override of its queryset for admin
@ -51,7 +47,7 @@ class Project(SimpleModel, SortableMixin):
class Meta: class Meta:
ordering = ['order'] ordering = ['order']
category = SortableForeignKey(Category) category = SortableForeignKey(Category, on_delete=models.CASCADE)
description = models.TextField() description = models.TextField()
order = models.PositiveIntegerField(default=0, editable=False) order = models.PositiveIntegerField(default=0, editable=False)
@ -63,7 +59,7 @@ class Credit(SortableMixin):
class Meta: class Meta:
ordering = ['order'] 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") first_name = models.CharField(max_length=30, help_text="Given name")
last_name = models.CharField(max_length=30, help_text="Family name") last_name = models.CharField(max_length=30, help_text="Family name")
@ -79,7 +75,7 @@ class Note(SortableMixin):
class Meta: class Meta:
ordering = ['order'] ordering = ['order']
project = models.ForeignKey(Project) project = models.ForeignKey(Project, on_delete=models.CASCADE)
text = models.CharField(max_length=100) text = models.CharField(max_length=100)
order = models.PositiveIntegerField(default=0, editable=False) 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 # Registered as a tabular inline on `Project` which can't be sorted
@python_2_unicode_compatible @python_2_unicode_compatible
class NonSortableCredit(models.Model): 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") first_name = models.CharField(max_length=30, help_text="Given name")
last_name = models.CharField(max_length=30, help_text="Family 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 # Registered as a stacked inline on `Project` which can't be sorted
@python_2_unicode_compatible @python_2_unicode_compatible
class NonSortableNote(models.Model): class NonSortableNote(models.Model):
project = models.ForeignKey(Project) project = models.ForeignKey(Project, on_delete=models.CASCADE)
text = models.CharField(max_length=100) text = models.CharField(max_length=100)
def __str__(self): def __str__(self):
@ -112,7 +108,7 @@ class NonSortableNote(models.Model):
# A generic bound model # A generic bound model
@python_2_unicode_compatible @python_2_unicode_compatible
class GenericNote(SimpleModel, SortableMixin): 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") verbose_name=u"Content type", related_name="generic_notes")
object_id = models.PositiveIntegerField(u"Content id") object_id = models.PositiveIntegerField(u"Content id")
content_object = GenericForeignKey(ct_field='content_type', content_object = GenericForeignKey(ct_field='content_type',
@ -133,7 +129,7 @@ class Component(SimpleModel, SortableMixin):
class Meta: class Meta:
ordering = ['order'] ordering = ['order']
widget = SortableForeignKey(Widget) widget = SortableForeignKey(Widget, on_delete=models.CASCADE)
order = models.PositiveIntegerField(default=0, editable=False) order = models.PositiveIntegerField(default=0, editable=False)
@ -183,7 +179,8 @@ class SortableCategoryWidget(SimpleModel, SortableMixin):
verbose_name = 'Sortable Category Widget' verbose_name = 'Sortable Category Widget'
verbose_name_plural = 'Sortable Category Widgets' 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) 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 that is *not* sortable, and is also not defined as an inline of the
SortableForeignKey field.""" SortableForeignKey field."""
non_sortable_category = SortableForeignKey(NonSortableCategory) non_sortable_category = SortableForeignKey(
NonSortableCategory, on_delete=models.CASCADE)
order = models.PositiveIntegerField(default=0, editable=False) order = models.PositiveIntegerField(default=0, editable=False)
@ -229,7 +227,7 @@ class CustomWidget(SortableMixin, SimpleModel):
@python_2_unicode_compatible @python_2_unicode_compatible
class CustomWidgetComponent(SortableMixin, SimpleModel): class CustomWidgetComponent(SortableMixin, SimpleModel):
custom_widget = models.ForeignKey(CustomWidget) custom_widget = models.ForeignKey(CustomWidget, on_delete=models.CASCADE)
# custom field for ordering # custom field for ordering
widget_order = models.PositiveIntegerField(default=0, db_index=True, widget_order = models.PositiveIntegerField(default=0, db_index=True,
@ -253,3 +251,12 @@ class BackwardCompatibleWidget(Sortable, SimpleModel):
def __str__(self): def __str__(self):
return self.title 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']

View File

@ -1,16 +1,12 @@
try: try:
import httplib import httplib # Python 2
except ImportError: except ImportError:
import http.client as httplib import http.client as httplib # Python 3
from django import VERSION
if VERSION > (1, 8):
import uuid
import json import json
from django import VERSION import django
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.db import models from django.db import models
from django.test import TestCase from django.test import TestCase
@ -18,28 +14,7 @@ from django.test.client import Client
from adminsortable.models import SortableMixin from adminsortable.models import SortableMixin
from adminsortable.utils import get_is_sortable from adminsortable.utils import get_is_sortable
from app.models import Category, Person, Project from .models import Category, Person, Project, TestNonAutoFieldModel
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']
class SortableTestCase(TestCase): class SortableTestCase(TestCase):
@ -79,8 +54,12 @@ class SortableTestCase(TestCase):
return category return category
def test_new_user_is_authenticated(self): def test_new_user_is_authenticated(self):
if django.VERSION < (1, 10):
self.assertEqual(self.user.is_authenticated(), True, self.assertEqual(self.user.is_authenticated(), True,
'User is not authenticated') 'User is not authenticated')
else:
self.assertEqual(self.user.is_authenticated, True,
'User is not authenticated')
def test_new_user_is_staff(self): def test_new_user_is_staff(self):
self.assertEqual(self.user.is_staff, True, 'User is not staff') 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): def test_adminsortable_change_list_view(self):
self.client.login(username=self.user.username, self.client.login(username=self.user.username,
password=self.user_raw_password) password=self.user_raw_password)
response = self.client.get('/admin/app/category/sort/') response = self.client.get('/admin/samples/category/sort/')
self.assertEquals(response.status_code, httplib.OK, self.assertEqual(response.status_code, httplib.OK,
'Unable to reach sort view.') 'Unable to reach sort view.')
def make_test_categories(self): def make_test_categories(self):
@ -124,7 +103,7 @@ class SortableTestCase(TestCase):
return category1, category2, category3 return category1, category2, category3
def get_sorting_url(self, model): 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()) model.model_type_id())
def get_category_indexes(self, *categories): def get_category_indexes(self, *categories):
@ -135,7 +114,7 @@ class SortableTestCase(TestCase):
password=self.user_raw_password) password=self.user_raw_password)
self.assertTrue(logged_in, 'User is not logged in') 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, self.assertEqual(response.status_code, httplib.OK,
'Admin sort request failed.') 'Admin sort request failed.')
@ -185,8 +164,7 @@ class SortableTestCase(TestCase):
# make a normal POST # make a normal POST
response = self.client.post(self.get_sorting_url(Category), response = self.client.post(self.get_sorting_url(Category),
data=self.get_category_indexes(category1, category2, category3)) data=self.get_category_indexes(category1, category2, category3))
content = json.loads(response.content.decode(encoding='UTF-8'), content = json.loads(response.content.decode(encoding='UTF-8'))
'latin-1')
self.assertFalse(content.get('objects_sorted'), self.assertFalse(content.get('objects_sorted'),
'Objects should not have been sorted. An ajax post is required.') '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), response = self.client.post(self.get_sorting_url(Category),
data=self.get_category_indexes(category3, category2, category1), data=self.get_category_indexes(category3, category2, category1),
HTTP_X_REQUESTED_WITH='XMLHttpRequest') HTTP_X_REQUESTED_WITH='XMLHttpRequest')
content = json.loads(response.content.decode(encoding='UTF-8'), content = json.loads(response.content.decode(encoding='UTF-8'))
'latin-1')
self.assertTrue(content.get('objects_sorted'), self.assertTrue(content.get('objects_sorted'),
'Objects should have been sorted.') 'Objects should have been sorted.')
@ -256,8 +233,8 @@ class SortableTestCase(TestCase):
self.client.login(username=self.user.username, self.client.login(username=self.user.username,
password=self.user_raw_password) password=self.user_raw_password)
response = self.client.get('/admin/app/project/sort/') response = self.client.get('/admin/samples/project/sort/')
self.assertEquals(response.status_code, httplib.OK, self.assertEqual(response.status_code, httplib.OK,
'Unable to reach sort view.') 'Unable to reach sort view.')
def test_adminsortable_change_list_view_permission_denied(self): def test_adminsortable_change_list_view_permission_denied(self):
@ -266,8 +243,8 @@ class SortableTestCase(TestCase):
self.client.login(username=self.staff.username, self.client.login(username=self.staff.username,
password=self.staff_raw_password) password=self.staff_raw_password)
response = self.client.get('/admin/app/project/sort/') response = self.client.get('/admin/samples/project/sort/')
self.assertEquals(response.status_code, httplib.FORBIDDEN, self.assertEqual(response.status_code, httplib.FORBIDDEN,
'Sort view must be forbidden.') 'Sort view must be forbidden.')
def test_adminsortable_inline_changelist_success(self): def test_adminsortable_inline_changelist_success(self):
@ -291,8 +268,7 @@ class SortableTestCase(TestCase):
response.status_code, response.status_code,
httplib.OK, httplib.OK,
'Note inline must be sortable in ProjectAdmin') 'Note inline must be sortable in ProjectAdmin')
content = json.loads(response.content.decode(encoding='UTF-8'), content = json.loads(response.content.decode(encoding='UTF-8'))
'latin-1')
self.assertTrue(content.get('objects_sorted'), self.assertTrue(content.get('objects_sorted'),
'Objects should have been sorted.') 'Objects should have been sorted.')
@ -317,8 +293,5 @@ class SortableTestCase(TestCase):
self.assertEqual(notes, expected_notes) self.assertEqual(notes, expected_notes)
def test_save_non_auto_field_model(self): def test_save_non_auto_field_model(self):
if VERSION > (1, 8):
model = TestNonAutoFieldModel() model = TestNonAutoFieldModel()
model.save() model.save()
else:
pass

View File

@ -1,7 +1,7 @@
from setuptools import setup, find_packages from setuptools import setup, find_packages
try: try:
README = open('README').read() README = open('README.rst').read()
except: except:
README = None README = None

37
tox.ini 100644
View File

@ -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__.: