File: README.rst

package info (click to toggle)
python-django-adminsortable 2.0.10-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 536 kB
  • sloc: python: 501; sh: 24; makefile: 3
file content (629 lines) | stat: -rw-r--r-- 19,196 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
Django Admin Sortable
=====================

|Build Status|

Current version: 2.0.10

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,
enabling individual items or groups of items to be sortable.

Sorting model instances with a sortable parent:

.. figure:: http://res.cloudinary.com/alsoicode/image/upload/v1451237555/django-admin-sortable/sortable-models.jpg
   :alt: sortable-models

   sortable-models

Sorting inlines:

.. figure:: http://res.cloudinary.com/alsoicode/image/upload/v1451237555/django-admin-sortable/sortable-inlines.jpg
   :alt: sortable-inlines

   sortable-inlines

Supported Django Versions
-------------------------

If you're using Django 1.4.x, use django-admin-sortable 1.4.9 or below.
For Django 1.5.x or higher, use the latest version of
django-admin-sortable.

django-admin-sortable 1.5.2 introduced backward-incompatible changes for
Django 1.4.x

django-admin-sortable 1.6.6 introduced a backward-incompatible change
for the ``sorting_filters`` attribute. Please convert your attributes to
the new tuple-based format.

django-admin-sortable 1.7.1 and higher are compatible with Python 3.

Installation
------------

1. ``$ pip install django-admin-sortable``

--or--

Download django-admin-sortable from
`source <https://github.com/iambrandontaylor/django-admin-sortable/archive/master.zip>`__

1. Unzip the directory and cd into the uncompressed project directory
2. 

   -  Optional: Enable your virtualenv

3. Run ``$ python setup.py install`` or add ``adminsortable`` to your
   PYTHONPATH.

Configuration
-------------

1. Add ``adminsortable`` to your ``INSTALLED_APPS``.
2. Ensure ``django.core.context_processors.static`` is in your
   ``TEMPLATE_CONTEXT_PROCESSORS``.

Static Media
~~~~~~~~~~~~

Preferred: Use the `staticfiles
app <https://docs.djangoproject.com/en/1.6/ref/contrib/staticfiles/>`__

Alternate: Copy the ``adminsortable`` folder from the ``static`` folder
to the location you serve static files from.

Testing
~~~~~~~

Have a look at the included sample\_project to see working examples. The
login credentials for admin are: admin/admin

When a model is sortable, a tool-area link will be added that says
"Change Order". Click this link, and you will be taken to the custom
view where you can drag-and-drop the records into order.

Inlines may be drag-and-dropped into any order directly from the change
form.

Usage
-----

Models
~~~~~~

To add "sortability" to a model, you need to inherit ``SortableMixin``
and at minimum, define:

-  The field which should be used for ``Meta.ordering``, which must
   resolve to one of the integer fields defined in Django's ORM:
-  ``PositiveIntegerField``
-  ``IntegerField``
-  ``PositiveSmallIntegerField``
-  ``SmallIntegerField``
-  ``BigIntegerField``

-  ``Meta.ordering`` **must only contain one value**, otherwise, your
   objects will not be sorted correctly.
-  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:

::

    # models.py
    from adminsortable.models import SortableMixin

    class MySortableClass(SortableMixin):
        class Meta:
            verbose_name = 'My Sortable Class'
            verbose_name_plural = 'My Sortable Classes'
            ordering = ['the_order']

        title = models.CharField(max_length=50)

        # define the field the model should be ordered by
        the_order = models.PositiveIntegerField(default=0, editable=False, db_index=True)

        def __unicode__(self):
            return self.title

Common Use Case
^^^^^^^^^^^^^^^

A common use case is to have child objects that are sortable relative to
a parent. If your parent object is also sortable, here's how you would
set up your models and admin options:

::

    # models.py
    from adminsortable.fields import SortableForeignKey

    class Category(SortableMixin):
        class Meta:
            ordering = ['category_order']
            verbose_name_plural = 'Categories'

        title = models.CharField(max_length=50)

        # ordering field
        category_order = models.PositiveIntegerField(default=0, editable=False, db_index=True)

    class Project(SortableMixin):
        class Meta:
            ordering = ['project_order']

        category = SortableForeignKey(Category)
        title = models.CharField(max_length=50)

        # ordering field
        project_order = models.PositiveIntegerField(default=0, editable=False, db_index=True)

        def __unicode__(self):
            return self.title

    # admin.py
    from adminsortable.admin import SortableAdmin

    from your_app.models import Category, Project

    admin.site.register(Category, SortableAdmin)
    admin.site.register(Project, SortableAdmin)

Sometimes you might have a parent model that is not sortable, but has
child models that are. In that case define your models and admin options
as such:

::

    from adminsortable.fields import SortableForeignKey

    # models.py
    class Category(models.Model):
        class Meta:
            verbose_name_plural = 'Categories'

        title = models.CharField(max_length=50)
        ...

    class Project(SortableMixin):
        class Meta:
            ordering = ['project_order']

        category = SortableForeignKey(Category)
        title = models.CharField(max_length=50)

        # ordering field
        project_order = models.PositiveIntegerField(default=0, editable=False, db_index=True)

        def __unicode__(self):
            return self.title

    # admin
    from adminsortable.admin import NonSortableParentAdmin, SortableStackedInline

    from your_app.models import Category, Project

    class ProjectInline(SortableStackedInline):
        model = Project
        extra = 1

    class CategoryAdmin(NonSortableParentAdmin):
        inlines = [ProjectInline]

    admin.site.register(Category, CategoryAdmin)

The ``NonSortableParentAdmin`` class is necessary to wire up the
additional URL patterns and JavaScript that Django Admin Sortable needs
to make your models sortable. The child model does not have to be an
inline model, it can be wired directly to Django admin and the objects
will be grouped by the non-sortable foreign key when sorting.

Backwards Compatibility
~~~~~~~~~~~~~~~~~~~~~~~

If you previously used Django Admin Sortable, **DON'T PANIC** -
everything will still work exactly as before ***without any changes to
your code***. Going forward, it is recommended that you use the new
``SortableMixin`` on your models, as pre-2.0 compatibility might not be
a permanent thing.

Please note however that the ``Sortable`` class still contains the
hard-coded ``order`` field, and meta inheritance requirements:

::

    # legacy model definition

    from adminsortable.models import Sortable

    class Project(Sortable):
        class Meta(Sortable.Meta):
            pass
        title = models.CharField(max_length=50)

        def __unicode__(self):
            return self.title

Model Instance Methods
^^^^^^^^^^^^^^^^^^^^^^

Each instance of a sortable model has two convenience methods to get the
next or previous instance:

::

    .get_next()
    .get_previous()

By default, these methods will respect their order in relation to a
``SortableForeignKey`` field, if present. Meaning, that given the
following data:

::

    | Parent Model 1 |               |
    |                | Child Model 1 |
    |                | Child Model 2 |
    | Parent Model 2 |               |
    |                | Child Model 3 |
    |                | Child Model 4 |
    |                | Child Model 5 |

"Child Model 2" ``get_next()`` would return ``None`` "Child Model 3"
``get_previous`` would return ``None``

If you wish to override this behavior, pass in:
``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,
should you need to:

::

    your_instance.get_next(extra_filters={'title__icontains': 'blue'})

Adding Sorting to an existing model
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Django 1.6.x or below
^^^^^^^^^^^^^^^^^^^^^

If you're adding Sorting to an existing model, it is recommended that
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
create a data migration in order to add the appropriate values for the
"order" column.

Example assuming a model named "Category":

::

    def forwards(self, orm):
        for index, category in enumerate(orm.Category.objects.all()):
            category.order = index + 1
            category.save()

See: `this
link <http://south.readthedocs.org/en/latest/tutorial/part3.html>`__ for
more information on South Data Migrations.

Django 1.7.x or higher
^^^^^^^^^^^^^^^^^^^^^^

Since schema migrations are built into Django 1.7, you don't have to use
south, but the process of adding and running migrations is nearly
identical. Take a look at the
`Migrations <https://docs.djangoproject.com/en/1.7/topics/migrations/>`__
documentation to get started.

Django Admin Integration
~~~~~~~~~~~~~~~~~~~~~~~~

To enable sorting in the admin, you need to inherit from
``SortableAdmin``:

::

    from django.contrib import admin
    from myapp.models import MySortableClass
    from adminsortable.admin import SortableAdmin

    class MySortableAdminClass(SortableAdmin):
        """Any admin options you need go here"""

    admin.site.register(MySortableClass, MySortableAdminClass)

To enable sorting on TabularInline models, you need to inherit from
SortableTabularInline:

::

    from adminsortable.admin import SortableTabularInline

    class MySortableTabularInline(SortableTabularInline):
       """Your inline options go here"""

To enable sorting on StackedInline models, you need to inherit from
SortableStackedInline:

::

    from adminsortable.admin import SortableStackedInline

    class MySortableStackedInline(SortableStackedInline):
       """Your inline options go here"""

There are also generic equivalents that you can inherit from:

::

    from adminsortable.admin import (SortableGenericTabularInline,
        SortableGenericStackedInline)
        """Your generic inline options go here"""

If your parent model is *not* sortable, but has child inlines that are,
your parent model needs to inherit from ``NonSortableParentAdmin``:

::

    from adminsortable.admin import (NonSortableParentAdmin,
        SortableTabularInline)

    class ChildTabularInline(SortableTabularInline):
        model = YourModel

    class ParentAdmin(NonSortableParentAdmin):
        inlines = [ChildTabularInline]

Overriding ``queryset()``
^^^^^^^^^^^^^^^^^^^^^^^^^

django-admin-sortable supports custom queryset overrides on admin models
and inline models in Django admin!

If you're providing an override of a SortableAdmin or Sortable inline
model, you don't need to do anything extra. django-admin-sortable will
automatically honor your queryset.

Have a look at the WidgetAdmin class in the sample project for an
example of an admin class with a custom ``queryset()`` override.

Overriding ``queryset()`` for an inline model
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

This is a special case, which requires a few lines of extra code to
properly determine the sortability of your model. Example:

::

    # add this import to your admin.py
    from adminsortable.utils import get_is_sortable


    class ComponentInline(SortableStackedInline):
        model = Component

        def queryset(self, request):
            qs = super(ComponentInline, self).queryset(request).filter(
                title__icontains='foo')

            # You'll need to add these lines to determine if your model
            # is sortable once we hit the change_form() for the parent model.

            if get_is_sortable(qs):
                self.model.is_sortable = True
            else:
                self.model.is_sortable = False
            return qs

If you override the queryset of an inline, the number of objects present
may change, and adminsortable won't be able to automatically determine
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.

Sorting subsets of objects
^^^^^^^^^^^^^^^^^^^^^^^^^^

It is also possible to sort a subset of objects in your model by adding
a ``sorting_filters`` tuple. This works exactly the same as
``.filter()`` on a QuerySet, and is applied *after* ``get_queryset()``
on the admin class, allowing you to override the queryset as you would
normally in admin but apply additional filters for sorting. The text
"Change Order of" will appear before each filter in the Change List
template, and the filter groups are displayed from left to right in the
order listed. If no ``sorting_filters`` are specified, the text "Change
Order" will be displayed for the link.

Self-Referential SortableForeignKey
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

You can specify a self-referential SortableForeignKey field, however the
admin interface will currently show a model that is a grandchild at the
same level as a child. I'm working to resolve this issue.

Important!
''''''''''

django-admin-sortable 1.6.6 introduced a backwards-incompatible change
for ``sorting_filters``. Previously this attribute was defined as a
dictionary, so you'll need to change your values over to the new
tuple-based format.

An example of sorting subsets would be a "Board of Directors". In this
use case, you have a list of "People" objects. Some of these people are
on the Board of Directors and some not, and you need to sort them
independently.

::

    class Person(Sortable):
        class Meta(Sortable.Meta):
            verbose_name_plural = 'People'

        first_name = models.CharField(max_length=50)
        last_name = models.CharField(max_length=50)
        is_board_member = models.BooleanField('Board Member', default=False)

        sorting_filters = (
            ('Board Members', {'is_board_member': True}),
            ('Non-Board Members', {'is_board_member': False}),
        )

        def __unicode__(self):
            return '{} {}'.format(self.first_name, self.last_name)

Extending custom templates
^^^^^^^^^^^^^^^^^^^^^^^^^^

By default, adminsortable's change form and change list views inherit
from Django admin's standard templates. Sometimes you need to have a
custom change form or change list, but also need adminsortable's CSS and
JavaScript for inline models that are sortable for example.

SortableAdmin has two attributes you can override for this use case:

::

    change_form_template_extends
    change_list_template_extends

These attributes have default values of:

::

    change_form_template_extends = 'admin/change_form.html'
    change_list_template_extends = 'admin/change_list.html'

If you need to extend the inline change form templates, you'll need to
select the right one, depending on your version of Django. For Django
1.5.x or below, you'll need to extend one of the following:

::

    templates/adminsortable/edit_inline/stacked-1.5.x.html
    templates/adminsortable/edit_inline/tabular-inline-1.5.x.html

For Django 1.6.x, extend:

::

    templates/adminsortable/edit_inline/stacked.html
    templates/adminsortable/edit_inline/tabular.html

A Special Note About Stacked Inlines...
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The height of a stacked inline model can dynamically increase, which can
make them difficult to sort. If you anticipate the height of a stacked
inline is going to be very tall, I would suggest using
SortableTabularInline instead.

Django-CMS integration
~~~~~~~~~~~~~~~~~~~~~~

Django-CMS plugins use their own change form, and thus won't
automatically include the necessary JavaScript for django-admin-sortable
to work. Fortunately, this is easy to resolve, as the ``CMSPlugin``
class allows a change form template to be specified:

::

    # example plugin
    from cms.plugin_base import CMSPluginBase

    class CMSCarouselPlugin(CMSPluginBase):
        admin_preview = False
        change_form_template = 'cms/sortable-stacked-inline-change-form.html'
        inlines = [SlideInline]
        model = Carousel
        name = _('Carousel')
        render_template = 'carousels/carousel.html'

        def render(self, context, instance, placeholder):
            context.update({
                'carousel': instance,
                'placeholder': placeholder
            })
            return context

    plugin_pool.register_plugin(CMSCarouselPlugin)

The contents of ``sortable-stacked-inline-change-form.html`` at a
minimum need to extend the extrahead block with:

::

    {% extends "admin/cms/page/plugin_change_form.html" %}
    {% load static from staticfiles %}

    {% block extrahead %}
        {{ block.super }}
        <script type="text/javascript" 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 type="text/javascript" src="{% static 'adminsortable/js/admin.sortable.stacked.inlines.js' %}"></script>

        <link rel="stylesheet" type="text/css" href="{% static 'adminsortable/css/admin.sortable.inline.css' %}" />
    {% endblock extrahead %}

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:

::

    <script src="{% static 'adminsortable/js/admin.sortable.stacked.inlines.js' %}"></script>

with:

::

    <script src="{% static 'adminsortable/js/admin.sortable.tabular.inlines.js' %}"></script>

Rationale
~~~~~~~~~

Other projects have added drag-and-drop ordering to the ChangeList view,
however this introduces a couple of problems...

-  The ChangeList view supports pagination, which makes drag-and-drop
   ordering across pages impossible.
-  The ChangeList view by default, does not order records based on a
   foreign key, nor distinguish between rows that are associated with a
   foreign key. This makes ordering the records grouped by a foreign key
   impossible.
-  The ChangeList supports in-line editing, and adding drag-and-drop
   ordering on top of that just seemed a little much in my opinion.

Status
~~~~~~

django-admin-sortable is currently used in production.

What's new in 2.0.10?
~~~~~~~~~~~~~~~~~~~~~

-  Bugfix for accessing custom ``order`` property of model. Thanks
   [@theithec](https://github.com/theithec) for reporting the issue.

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.

License
~~~~~~~

django-admin-sortable is released under the Apache Public License v2.

.. |Build Status| image:: https://travis-ci.org/iambrandontaylor/django-admin-sortable.svg?branch=master
   :target: https://travis-ci.org/iambrandontaylor/django-admin-sortable