2011-09-01 00:51:02 +00:00
|
|
|
import json
|
2020-05-26 19:15:12 +00:00
|
|
|
from urllib.parse import urlencode
|
2013-03-11 00:53:05 +00:00
|
|
|
|
2011-09-01 00:51:02 +00:00
|
|
|
from django.conf import settings
|
2021-07-16 23:05:59 +00:00
|
|
|
from django.conf.urls import re_path
|
2011-09-04 03:02:48 +00:00
|
|
|
from django.contrib.admin import ModelAdmin, TabularInline, StackedInline
|
|
|
|
|
from django.contrib.admin.options import InlineModelAdmin
|
2019-04-17 15:22:21 +00:00
|
|
|
from django.contrib.admin.views.main import IGNORED_PARAMS, PAGE_VAR
|
2017-03-16 13:22:27 +00:00
|
|
|
from django.contrib.contenttypes.admin import (GenericStackedInline,
|
|
|
|
|
GenericTabularInline)
|
2011-09-01 00:51:02 +00:00
|
|
|
from django.contrib.contenttypes.models import ContentType
|
2016-06-16 09:16:42 +00:00
|
|
|
from django.core.exceptions import PermissionDenied
|
2020-05-24 10:07:12 +00:00
|
|
|
from django.db import transaction
|
2021-07-16 23:05:59 +00:00
|
|
|
from django.http import JsonResponse
|
2019-06-03 18:13:21 +00:00
|
|
|
from django.shortcuts import render
|
2011-09-01 00:51:02 +00:00
|
|
|
from django.template.defaultfilters import capfirst
|
2016-06-16 09:16:42 +00:00
|
|
|
from django.utils.decorators import method_decorator
|
2020-05-24 10:07:12 +00:00
|
|
|
from django.utils.translation import gettext as _
|
2016-06-16 09:16:42 +00:00
|
|
|
from django.views.decorators.http import require_POST
|
2011-09-01 00:51:02 +00:00
|
|
|
|
2015-12-23 21:39:45 +00:00
|
|
|
from adminsortable.fields import SortableForeignKey
|
2015-08-24 02:25:55 +00:00
|
|
|
from adminsortable.models import SortableMixin
|
2016-01-27 16:26:03 +00:00
|
|
|
from adminsortable.utils import get_is_sortable
|
2011-09-01 00:51:02 +00:00
|
|
|
|
|
|
|
|
STATIC_URL = settings.STATIC_URL
|
|
|
|
|
|
|
|
|
|
|
2013-04-28 02:58:02 +00:00
|
|
|
class SortableAdminBase(object):
|
2014-09-21 19:12:30 +00:00
|
|
|
sortable_change_list_with_sort_link_template = \
|
|
|
|
|
'adminsortable/change_list_with_sort_link.html'
|
|
|
|
|
sortable_change_form_template = 'adminsortable/change_form.html'
|
|
|
|
|
sortable_change_list_template = 'adminsortable/change_list.html'
|
|
|
|
|
|
|
|
|
|
change_form_template_extends = 'admin/change_form.html'
|
|
|
|
|
change_list_template_extends = 'admin/change_list.html'
|
|
|
|
|
|
2018-06-18 15:40:24 +00:00
|
|
|
after_sorting_js_callback_name = None
|
|
|
|
|
|
2019-02-21 14:56:08 +00:00
|
|
|
def get_querystring_filters(self, request):
|
|
|
|
|
filters = {}
|
|
|
|
|
|
|
|
|
|
for k, v in request.GET.items():
|
2019-04-17 15:22:21 +00:00
|
|
|
if k not in IGNORED_PARAMS and k != PAGE_VAR:
|
2019-02-22 10:14:07 +00:00
|
|
|
filters[k] = v
|
2019-02-21 14:56:08 +00:00
|
|
|
|
|
|
|
|
return filters
|
|
|
|
|
|
2013-04-28 02:58:02 +00:00
|
|
|
def changelist_view(self, request, extra_context=None):
|
|
|
|
|
"""
|
|
|
|
|
If the model that inherits Sortable has more than one object,
|
|
|
|
|
its sort order can be changed. This view adds a link to the
|
|
|
|
|
object_tools block to take people to the view to change the sorting.
|
|
|
|
|
"""
|
2019-02-14 21:04:17 +00:00
|
|
|
|
|
|
|
|
# apply any filters via the querystring
|
2019-02-21 14:56:08 +00:00
|
|
|
filters = self.get_querystring_filters(request)
|
2019-02-14 21:04:17 +00:00
|
|
|
|
|
|
|
|
# Check if the filtered queryset contains more than 1 item
|
|
|
|
|
# to enable sort link
|
|
|
|
|
queryset = self.get_queryset(request).filter(**filters)
|
|
|
|
|
self.is_sortable = False
|
|
|
|
|
|
|
|
|
|
if get_is_sortable(queryset):
|
2013-04-28 02:58:02 +00:00
|
|
|
self.change_list_template = \
|
|
|
|
|
self.sortable_change_list_with_sort_link_template
|
|
|
|
|
self.is_sortable = True
|
2013-05-03 12:35:17 +00:00
|
|
|
|
|
|
|
|
if extra_context is None:
|
|
|
|
|
extra_context = {}
|
|
|
|
|
|
|
|
|
|
extra_context.update({
|
2014-03-05 14:10:47 +00:00
|
|
|
'change_list_template_extends': self.change_list_template_extends,
|
2014-09-06 16:38:00 +00:00
|
|
|
'sorting_filters': [sort_filter[0] for sort_filter
|
2019-02-14 21:04:17 +00:00
|
|
|
in getattr(self.model, 'sorting_filters', [])],
|
|
|
|
|
'is_sortable': self.is_sortable
|
2013-05-03 12:35:17 +00:00
|
|
|
})
|
2019-02-14 21:04:17 +00:00
|
|
|
|
2013-04-28 02:58:02 +00:00
|
|
|
return super(SortableAdminBase, self).changelist_view(request,
|
|
|
|
|
extra_context=extra_context)
|
|
|
|
|
|
2018-07-09 11:49:55 +00:00
|
|
|
# override this function in your SortableAdmin if you need to do something
|
|
|
|
|
# after sorting has occurred
|
|
|
|
|
def after_sorting(self):
|
|
|
|
|
pass
|
|
|
|
|
|
2013-04-28 02:58:02 +00:00
|
|
|
|
|
|
|
|
class SortableAdmin(SortableAdminBase, ModelAdmin):
|
2012-09-23 18:37:58 +00:00
|
|
|
"""
|
2013-03-11 00:53:05 +00:00
|
|
|
Admin class to add template overrides and context objects to enable
|
|
|
|
|
drag-and-drop ordering.
|
2012-09-23 18:37:58 +00:00
|
|
|
"""
|
2013-05-03 12:35:17 +00:00
|
|
|
|
2011-09-01 00:51:02 +00:00
|
|
|
class Meta:
|
|
|
|
|
abstract = True
|
|
|
|
|
|
2016-06-23 13:02:01 +00:00
|
|
|
@property
|
|
|
|
|
def has_sortable_tabular_inlines(self):
|
|
|
|
|
base_classes = (SortableTabularInline, SortableGenericTabularInline)
|
|
|
|
|
return any(issubclass(klass, base_classes) for klass in self.inlines)
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def has_sortable_stacked_inlines(self):
|
|
|
|
|
base_classes = (SortableStackedInline, SortableGenericStackedInline)
|
|
|
|
|
return any(issubclass(klass, base_classes) for klass in self.inlines)
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def change_form_template(self):
|
|
|
|
|
if self.has_sortable_tabular_inlines or self.has_sortable_stacked_inlines:
|
|
|
|
|
return self.sortable_change_form_template
|
|
|
|
|
return super(SortableAdmin, self).change_form_template
|
|
|
|
|
|
2011-09-01 00:51:02 +00:00
|
|
|
def get_urls(self):
|
|
|
|
|
urls = super(SortableAdmin, self).get_urls()
|
2017-03-16 14:13:13 +00:00
|
|
|
info = self.model._meta.app_label, self.model._meta.model_name
|
2016-06-16 09:16:42 +00:00
|
|
|
|
2016-10-30 15:33:20 +00:00
|
|
|
# this ajax view changes the order of instances of the model type
|
2021-07-16 23:05:59 +00:00
|
|
|
admin_do_sorting_url = re_path(
|
2016-06-16 09:16:42 +00:00
|
|
|
r'^sort/do-sorting/(?P<model_type_id>\d+)/$',
|
2015-12-21 19:11:13 +00:00
|
|
|
self.admin_site.admin_view(self.do_sorting_view),
|
2016-06-16 09:16:42 +00:00
|
|
|
name='%s_%s_do_sorting' % info)
|
2015-12-21 19:11:13 +00:00
|
|
|
|
|
|
|
|
# this view displays the sortable objects
|
2021-07-16 23:05:59 +00:00
|
|
|
admin_sort_url = re_path(
|
2016-06-16 09:16:42 +00:00
|
|
|
r'^sort/$',
|
2015-12-21 19:11:13 +00:00
|
|
|
self.admin_site.admin_view(self.sort_view),
|
2016-06-16 09:16:42 +00:00
|
|
|
name='%s_%s_sort' % info)
|
2015-12-21 19:11:13 +00:00
|
|
|
|
2016-06-15 13:54:07 +00:00
|
|
|
urls = [
|
|
|
|
|
admin_do_sorting_url,
|
|
|
|
|
admin_sort_url
|
|
|
|
|
] + urls
|
|
|
|
|
return urls
|
2011-09-01 00:51:02 +00:00
|
|
|
|
Improve performance of sort view for moods and elements.
* Use `{% include "..." with ... %}` instead of template tags that do
nothing but pass through or rename context variables and render a
template. This appears to yield a 2x increase in performance.
As a side effect, this change also appears to fix some glitches with
the rendering of `fa-sort`, `fa-sort-asc` and `fa-sort-desc` icons.
* Move queryset filtering from `sort_view()` to new `get_sort_view_queryset()`
method, so subclasses can override to apply different or additional
filtering (based on `request` and `sortable_by_expression`) to reduce
the number of objects being reordered.
`django-admin-sortable` already provides a mechanism to reorder a
subset of objects via `sorting_filters`, but this is restricted to a
small number of hard coded filters, and we found it not very useful.
We have tens of thousands of nested objects grouped under hundreds or
thousands of parent objects, and we needed a way to reorder child
objects just within their own group.
We also needed a way to reorder a subset of flat (not grouped by
parent) sortable objects with much more flexibility.
Here's an example of additional filtering that allows us to reorder a
contiguous sequence of objects (nested or flat) that bounded by the min
and max (by ordering) selected objects:
```python
class MyBaseSortableAdmin(SortableAdmin):
def get_sort_view_queryset(self, request, sortable_by_expression):
"""
Filter the sort view queryset to include only a contiguous sequence of
objects between the first and last of given parent objects, according
to the current ordering.
This should avoid inconsistent or ambiguous behaviour that might occur
when re-ordering a non-contiguous sequence.
"""
sortable_by_expression = sortable_by_expression or 'pk'
queryset = super(MyBaseSortableAdmin, self) \
.get_sort_view_queryset(request, sortable_by_expression)
pks = [
int(pk) for pk in request.GET.get('pks', '').split(',') if pk
]
if pks:
queryset = queryset.filter(**{
'%s__in' % sortable_by_expression: pks,
})
return queryset
def reorder_children(self, qs, child):
# Get the min and max order field value for the selected objects, then
# get contiguous PKs for objects between the min and max and pass to
# the sort view, to avoid inconsistent or ambiguous behaviour.
field = self.opts.ordering[0].replace('-', '')
qs = qs.model.objects.filter(**qs.aggregate(**{
'%s__gte' % field: Min(field),
'%s__lte' % field: Max(field),
}))
ct = ContentType.objects.get_for_model(child)
url = '%ssort/?pks=%s' % (
reverse('admin:%s_%s_changelist' % (ct.app_label, ct.model)),
','.join([str(pk) for pk in qs.values_list('pk', flat=True)]),
)
return http.HttpResponseRedirect(url)
class MyModelAdmin(MyBaseSortableAdmin):
actions = (
"reorder_mymodel",
"reorder_childmodel",
)
def reorder_mymodel(self, request, qs):
return self.reorder_children(qs, MyModel)
reorder_chapters.short_description = 'Reorder selected MyModels'
def reorder_childmodel(self, request, qs):
return self.reorder_children(qs, ChildModel)
reorder_elements.short_description = 'Reorder ChildModels for the selected MyModels'
```
This could be made generic enough for inclusion by default with a few
tweaks, so that `Reorder selected {{ parent.verbose_name_plural }}` and
`Reorder {{ child.verbose_name_plural }} for selected {{ parent.verbose_name_plural }}`
admin actions could be included in sortable change lists.
2018-03-13 12:05:35 +00:00
|
|
|
def get_sort_view_queryset(self, request, sortable_by_expression):
|
2011-09-01 00:51:02 +00:00
|
|
|
"""
|
Improve performance of sort view for moods and elements.
* Use `{% include "..." with ... %}` instead of template tags that do
nothing but pass through or rename context variables and render a
template. This appears to yield a 2x increase in performance.
As a side effect, this change also appears to fix some glitches with
the rendering of `fa-sort`, `fa-sort-asc` and `fa-sort-desc` icons.
* Move queryset filtering from `sort_view()` to new `get_sort_view_queryset()`
method, so subclasses can override to apply different or additional
filtering (based on `request` and `sortable_by_expression`) to reduce
the number of objects being reordered.
`django-admin-sortable` already provides a mechanism to reorder a
subset of objects via `sorting_filters`, but this is restricted to a
small number of hard coded filters, and we found it not very useful.
We have tens of thousands of nested objects grouped under hundreds or
thousands of parent objects, and we needed a way to reorder child
objects just within their own group.
We also needed a way to reorder a subset of flat (not grouped by
parent) sortable objects with much more flexibility.
Here's an example of additional filtering that allows us to reorder a
contiguous sequence of objects (nested or flat) that bounded by the min
and max (by ordering) selected objects:
```python
class MyBaseSortableAdmin(SortableAdmin):
def get_sort_view_queryset(self, request, sortable_by_expression):
"""
Filter the sort view queryset to include only a contiguous sequence of
objects between the first and last of given parent objects, according
to the current ordering.
This should avoid inconsistent or ambiguous behaviour that might occur
when re-ordering a non-contiguous sequence.
"""
sortable_by_expression = sortable_by_expression or 'pk'
queryset = super(MyBaseSortableAdmin, self) \
.get_sort_view_queryset(request, sortable_by_expression)
pks = [
int(pk) for pk in request.GET.get('pks', '').split(',') if pk
]
if pks:
queryset = queryset.filter(**{
'%s__in' % sortable_by_expression: pks,
})
return queryset
def reorder_children(self, qs, child):
# Get the min and max order field value for the selected objects, then
# get contiguous PKs for objects between the min and max and pass to
# the sort view, to avoid inconsistent or ambiguous behaviour.
field = self.opts.ordering[0].replace('-', '')
qs = qs.model.objects.filter(**qs.aggregate(**{
'%s__gte' % field: Min(field),
'%s__lte' % field: Max(field),
}))
ct = ContentType.objects.get_for_model(child)
url = '%ssort/?pks=%s' % (
reverse('admin:%s_%s_changelist' % (ct.app_label, ct.model)),
','.join([str(pk) for pk in qs.values_list('pk', flat=True)]),
)
return http.HttpResponseRedirect(url)
class MyModelAdmin(MyBaseSortableAdmin):
actions = (
"reorder_mymodel",
"reorder_childmodel",
)
def reorder_mymodel(self, request, qs):
return self.reorder_children(qs, MyModel)
reorder_chapters.short_description = 'Reorder selected MyModels'
def reorder_childmodel(self, request, qs):
return self.reorder_children(qs, ChildModel)
reorder_elements.short_description = 'Reorder ChildModels for the selected MyModels'
```
This could be made generic enough for inclusion by default with a few
tweaks, so that `Reorder selected {{ parent.verbose_name_plural }}` and
`Reorder {{ child.verbose_name_plural }} for selected {{ parent.verbose_name_plural }}`
admin actions could be included in sortable change lists.
2018-03-13 12:05:35 +00:00
|
|
|
Return a queryset, optionally filtered based on request and
|
|
|
|
|
`sortable_by_expression` to be used in the sort view.
|
2011-09-01 00:51:02 +00:00
|
|
|
"""
|
2014-03-05 14:10:47 +00:00
|
|
|
# get sort group index from querystring if present
|
|
|
|
|
sort_filter_index = request.GET.get('sort_filter')
|
2018-03-20 01:23:59 +00:00
|
|
|
|
2019-02-21 14:56:08 +00:00
|
|
|
# apply any filters via the querystring
|
|
|
|
|
filters = self.get_querystring_filters(request)
|
2018-05-16 13:05:40 +00:00
|
|
|
|
2014-03-05 14:10:47 +00:00
|
|
|
if sort_filter_index:
|
|
|
|
|
try:
|
|
|
|
|
filters = self.model.sorting_filters[int(sort_filter_index)][1]
|
2014-05-28 12:11:04 +00:00
|
|
|
except (IndexError, ValueError):
|
2014-03-05 14:10:47 +00:00
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
# Apply any sort filters to create a subset of sortable objects
|
2018-03-20 01:23:59 +00:00
|
|
|
return self.get_queryset(request).filter(**filters)
|
Improve performance of sort view for moods and elements.
* Use `{% include "..." with ... %}` instead of template tags that do
nothing but pass through or rename context variables and render a
template. This appears to yield a 2x increase in performance.
As a side effect, this change also appears to fix some glitches with
the rendering of `fa-sort`, `fa-sort-asc` and `fa-sort-desc` icons.
* Move queryset filtering from `sort_view()` to new `get_sort_view_queryset()`
method, so subclasses can override to apply different or additional
filtering (based on `request` and `sortable_by_expression`) to reduce
the number of objects being reordered.
`django-admin-sortable` already provides a mechanism to reorder a
subset of objects via `sorting_filters`, but this is restricted to a
small number of hard coded filters, and we found it not very useful.
We have tens of thousands of nested objects grouped under hundreds or
thousands of parent objects, and we needed a way to reorder child
objects just within their own group.
We also needed a way to reorder a subset of flat (not grouped by
parent) sortable objects with much more flexibility.
Here's an example of additional filtering that allows us to reorder a
contiguous sequence of objects (nested or flat) that bounded by the min
and max (by ordering) selected objects:
```python
class MyBaseSortableAdmin(SortableAdmin):
def get_sort_view_queryset(self, request, sortable_by_expression):
"""
Filter the sort view queryset to include only a contiguous sequence of
objects between the first and last of given parent objects, according
to the current ordering.
This should avoid inconsistent or ambiguous behaviour that might occur
when re-ordering a non-contiguous sequence.
"""
sortable_by_expression = sortable_by_expression or 'pk'
queryset = super(MyBaseSortableAdmin, self) \
.get_sort_view_queryset(request, sortable_by_expression)
pks = [
int(pk) for pk in request.GET.get('pks', '').split(',') if pk
]
if pks:
queryset = queryset.filter(**{
'%s__in' % sortable_by_expression: pks,
})
return queryset
def reorder_children(self, qs, child):
# Get the min and max order field value for the selected objects, then
# get contiguous PKs for objects between the min and max and pass to
# the sort view, to avoid inconsistent or ambiguous behaviour.
field = self.opts.ordering[0].replace('-', '')
qs = qs.model.objects.filter(**qs.aggregate(**{
'%s__gte' % field: Min(field),
'%s__lte' % field: Max(field),
}))
ct = ContentType.objects.get_for_model(child)
url = '%ssort/?pks=%s' % (
reverse('admin:%s_%s_changelist' % (ct.app_label, ct.model)),
','.join([str(pk) for pk in qs.values_list('pk', flat=True)]),
)
return http.HttpResponseRedirect(url)
class MyModelAdmin(MyBaseSortableAdmin):
actions = (
"reorder_mymodel",
"reorder_childmodel",
)
def reorder_mymodel(self, request, qs):
return self.reorder_children(qs, MyModel)
reorder_chapters.short_description = 'Reorder selected MyModels'
def reorder_childmodel(self, request, qs):
return self.reorder_children(qs, ChildModel)
reorder_elements.short_description = 'Reorder ChildModels for the selected MyModels'
```
This could be made generic enough for inclusion by default with a few
tweaks, so that `Reorder selected {{ parent.verbose_name_plural }}` and
`Reorder {{ child.verbose_name_plural }} for selected {{ parent.verbose_name_plural }}`
admin actions could be included in sortable change lists.
2018-03-13 12:05:35 +00:00
|
|
|
|
|
|
|
|
def sort_view(self, request):
|
|
|
|
|
"""
|
|
|
|
|
Custom admin view that displays the objects as a list whose sort
|
|
|
|
|
order can be changed via drag-and-drop.
|
|
|
|
|
"""
|
|
|
|
|
if not self.has_change_permission(request):
|
|
|
|
|
raise PermissionDenied
|
|
|
|
|
|
|
|
|
|
opts = self.model._meta
|
|
|
|
|
|
2021-07-16 23:05:59 +00:00
|
|
|
jquery_lib_path = 'admin/js/vendor/jquery/jquery.js'
|
2011-09-01 00:51:02 +00:00
|
|
|
|
2013-03-11 00:53:05 +00:00
|
|
|
# Determine if we need to regroup objects relative to a
|
|
|
|
|
# foreign key specified on the model class that is extending Sortable.
|
2012-11-02 13:04:32 +00:00
|
|
|
# Legacy support for 'sortable_by' defined as a model property
|
2012-02-25 04:35:30 +00:00
|
|
|
sortable_by_property = getattr(self.model, 'sortable_by', None)
|
|
|
|
|
|
2015-12-23 21:39:45 +00:00
|
|
|
# see if our model is sortable by a SortableForeignKey field
|
|
|
|
|
# and that the number of objects available is >= 2
|
|
|
|
|
sortable_by_fk = None
|
|
|
|
|
sortable_by_field_name = None
|
|
|
|
|
sortable_by_class_is_sortable = False
|
|
|
|
|
|
|
|
|
|
for field in self.model._meta.fields:
|
|
|
|
|
if isinstance(field, SortableForeignKey):
|
2021-07-16 23:05:59 +00:00
|
|
|
sortable_by_fk = field.remote_field.model
|
2015-12-23 21:39:45 +00:00
|
|
|
sortable_by_field_name = field.name.lower()
|
2020-05-20 01:37:55 +00:00
|
|
|
sortable_by_class_is_sortable = \
|
|
|
|
|
isinstance(sortable_by_fk, SortableMixin) and \
|
|
|
|
|
sortable_by_fk.objects.count() >= 2
|
2012-02-25 04:35:30 +00:00
|
|
|
|
|
|
|
|
if sortable_by_property:
|
2021-07-16 23:05:59 +00:00
|
|
|
sortable_by_class = self.model.sortable_by
|
|
|
|
|
sortable_by_expression = sortable_by_class.__name__.lower()
|
2011-11-23 02:42:36 +00:00
|
|
|
|
2013-03-11 00:53:05 +00:00
|
|
|
sortable_by_class_display_name = sortable_by_class._meta \
|
|
|
|
|
.verbose_name_plural
|
2011-11-23 04:19:39 +00:00
|
|
|
|
2012-02-25 04:35:30 +00:00
|
|
|
elif sortable_by_fk:
|
2013-03-11 00:53:05 +00:00
|
|
|
# get sortable by properties from the SortableForeignKey
|
|
|
|
|
# field - supported in 1.3+
|
2015-12-23 21:39:45 +00:00
|
|
|
sortable_by_class_display_name = sortable_by_fk._meta.verbose_name_plural
|
|
|
|
|
sortable_by_class = sortable_by_fk
|
|
|
|
|
sortable_by_expression = sortable_by_field_name
|
2011-11-23 04:19:39 +00:00
|
|
|
|
2011-09-01 00:51:02 +00:00
|
|
|
else:
|
2012-11-02 13:04:32 +00:00
|
|
|
# model is not sortable by another model
|
2013-03-11 00:53:05 +00:00
|
|
|
sortable_by_class = sortable_by_expression = \
|
|
|
|
|
sortable_by_class_display_name = \
|
|
|
|
|
sortable_by_class_is_sortable = None
|
2011-09-01 00:51:02 +00:00
|
|
|
|
Improve performance of sort view for moods and elements.
* Use `{% include "..." with ... %}` instead of template tags that do
nothing but pass through or rename context variables and render a
template. This appears to yield a 2x increase in performance.
As a side effect, this change also appears to fix some glitches with
the rendering of `fa-sort`, `fa-sort-asc` and `fa-sort-desc` icons.
* Move queryset filtering from `sort_view()` to new `get_sort_view_queryset()`
method, so subclasses can override to apply different or additional
filtering (based on `request` and `sortable_by_expression`) to reduce
the number of objects being reordered.
`django-admin-sortable` already provides a mechanism to reorder a
subset of objects via `sorting_filters`, but this is restricted to a
small number of hard coded filters, and we found it not very useful.
We have tens of thousands of nested objects grouped under hundreds or
thousands of parent objects, and we needed a way to reorder child
objects just within their own group.
We also needed a way to reorder a subset of flat (not grouped by
parent) sortable objects with much more flexibility.
Here's an example of additional filtering that allows us to reorder a
contiguous sequence of objects (nested or flat) that bounded by the min
and max (by ordering) selected objects:
```python
class MyBaseSortableAdmin(SortableAdmin):
def get_sort_view_queryset(self, request, sortable_by_expression):
"""
Filter the sort view queryset to include only a contiguous sequence of
objects between the first and last of given parent objects, according
to the current ordering.
This should avoid inconsistent or ambiguous behaviour that might occur
when re-ordering a non-contiguous sequence.
"""
sortable_by_expression = sortable_by_expression or 'pk'
queryset = super(MyBaseSortableAdmin, self) \
.get_sort_view_queryset(request, sortable_by_expression)
pks = [
int(pk) for pk in request.GET.get('pks', '').split(',') if pk
]
if pks:
queryset = queryset.filter(**{
'%s__in' % sortable_by_expression: pks,
})
return queryset
def reorder_children(self, qs, child):
# Get the min and max order field value for the selected objects, then
# get contiguous PKs for objects between the min and max and pass to
# the sort view, to avoid inconsistent or ambiguous behaviour.
field = self.opts.ordering[0].replace('-', '')
qs = qs.model.objects.filter(**qs.aggregate(**{
'%s__gte' % field: Min(field),
'%s__lte' % field: Max(field),
}))
ct = ContentType.objects.get_for_model(child)
url = '%ssort/?pks=%s' % (
reverse('admin:%s_%s_changelist' % (ct.app_label, ct.model)),
','.join([str(pk) for pk in qs.values_list('pk', flat=True)]),
)
return http.HttpResponseRedirect(url)
class MyModelAdmin(MyBaseSortableAdmin):
actions = (
"reorder_mymodel",
"reorder_childmodel",
)
def reorder_mymodel(self, request, qs):
return self.reorder_children(qs, MyModel)
reorder_chapters.short_description = 'Reorder selected MyModels'
def reorder_childmodel(self, request, qs):
return self.reorder_children(qs, ChildModel)
reorder_elements.short_description = 'Reorder ChildModels for the selected MyModels'
```
This could be made generic enough for inclusion by default with a few
tweaks, so that `Reorder selected {{ parent.verbose_name_plural }}` and
`Reorder {{ child.verbose_name_plural }} for selected {{ parent.verbose_name_plural }}`
admin actions could be included in sortable change lists.
2018-03-13 12:05:35 +00:00
|
|
|
objects = self.get_sort_view_queryset(request, sortable_by_expression)
|
|
|
|
|
|
2012-02-25 04:35:30 +00:00
|
|
|
if sortable_by_property or sortable_by_fk:
|
2013-03-11 00:53:05 +00:00
|
|
|
# Order the objects by the property they are sortable by,
|
2013-04-28 02:58:02 +00:00
|
|
|
# then by the order, otherwise the regroup
|
2013-03-11 00:53:05 +00:00
|
|
|
# template tag will not show the objects correctly
|
2016-01-27 15:58:58 +00:00
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
order_field_name = opts.model._meta.ordering[0]
|
2016-03-14 15:09:18 +00:00
|
|
|
except (AttributeError, IndexError):
|
2016-01-27 15:58:58 +00:00
|
|
|
order_field_name = 'order'
|
|
|
|
|
|
|
|
|
|
objects = objects.order_by(sortable_by_expression, order_field_name)
|
2012-02-25 04:35:30 +00:00
|
|
|
|
2011-09-01 00:51:02 +00:00
|
|
|
try:
|
|
|
|
|
verbose_name_plural = opts.verbose_name_plural.__unicode__()
|
|
|
|
|
except AttributeError:
|
|
|
|
|
verbose_name_plural = opts.verbose_name_plural
|
|
|
|
|
|
2021-07-16 23:05:59 +00:00
|
|
|
context = self.admin_site.each_context(request)
|
2016-11-03 01:29:31 +00:00
|
|
|
|
2020-05-24 09:46:19 +00:00
|
|
|
filters = urlencode(self.get_querystring_filters(request))
|
|
|
|
|
|
2016-11-02 16:47:36 +00:00
|
|
|
context.update({
|
2013-04-30 12:36:46 +00:00
|
|
|
'title': u'Drag and drop {0} to change display order'.format(
|
2013-03-11 00:53:05 +00:00
|
|
|
capfirst(verbose_name_plural)),
|
2012-11-02 13:04:32 +00:00
|
|
|
'opts': opts,
|
2016-06-16 09:16:42 +00:00
|
|
|
'has_perm': True,
|
2012-11-02 13:04:32 +00:00
|
|
|
'objects': objects,
|
|
|
|
|
'group_expression': sortable_by_expression,
|
|
|
|
|
'sortable_by_class': sortable_by_class,
|
|
|
|
|
'sortable_by_class_is_sortable': sortable_by_class_is_sortable,
|
2015-12-08 21:04:05 +00:00
|
|
|
'sortable_by_class_display_name': sortable_by_class_display_name,
|
2020-05-24 09:46:19 +00:00
|
|
|
'filters': filters,
|
2016-02-16 13:48:32 +00:00
|
|
|
'jquery_lib_path': jquery_lib_path,
|
2018-06-18 15:40:24 +00:00
|
|
|
'csrf_cookie_name': getattr(settings, 'CSRF_COOKIE_NAME', 'csrftoken'),
|
2019-01-17 18:32:02 +00:00
|
|
|
'csrf_header_name': getattr(settings, 'CSRF_HEADER_NAME', 'X-CSRFToken'),
|
2018-06-18 15:40:24 +00:00
|
|
|
'after_sorting_js_callback_name': self.after_sorting_js_callback_name
|
2016-11-02 16:47:36 +00:00
|
|
|
})
|
2012-09-23 18:37:58 +00:00
|
|
|
return render(request, self.sortable_change_list_template, context)
|
2011-09-01 00:51:02 +00:00
|
|
|
|
2013-06-20 19:47:41 +00:00
|
|
|
def add_view(self, request, form_url='', extra_context=None):
|
|
|
|
|
if extra_context is None:
|
|
|
|
|
extra_context = {}
|
|
|
|
|
|
|
|
|
|
extra_context.update({
|
|
|
|
|
'change_form_template_extends': self.change_form_template_extends
|
|
|
|
|
})
|
|
|
|
|
return super(SortableAdmin, self).add_view(request, form_url,
|
|
|
|
|
extra_context=extra_context)
|
|
|
|
|
|
2014-09-04 20:07:55 +00:00
|
|
|
def change_view(self, request, object_id, form_url='', extra_context=None):
|
2013-04-28 02:58:02 +00:00
|
|
|
|
2013-05-03 12:35:17 +00:00
|
|
|
if extra_context is None:
|
|
|
|
|
extra_context = {}
|
|
|
|
|
|
|
|
|
|
extra_context.update({
|
2016-02-23 17:25:18 +00:00
|
|
|
'change_form_template_extends': self.change_form_template_extends,
|
2016-06-23 13:02:01 +00:00
|
|
|
'has_sortable_tabular_inlines': self.has_sortable_tabular_inlines,
|
|
|
|
|
'has_sortable_stacked_inlines': self.has_sortable_stacked_inlines,
|
2018-06-18 15:40:24 +00:00
|
|
|
'csrf_cookie_name': getattr(settings, 'CSRF_COOKIE_NAME', 'csrftoken'),
|
2019-01-17 18:32:02 +00:00
|
|
|
'csrf_header_name': getattr(settings, 'CSRF_HEADER_NAME', 'X-CSRFToken'),
|
2018-06-18 15:40:24 +00:00
|
|
|
'after_sorting_js_callback_name': self.after_sorting_js_callback_name
|
2013-05-03 12:35:17 +00:00
|
|
|
})
|
|
|
|
|
|
2013-03-11 00:53:05 +00:00
|
|
|
return super(SortableAdmin, self).change_view(request, object_id,
|
2014-09-04 20:07:55 +00:00
|
|
|
form_url='', extra_context=extra_context)
|
2011-09-01 00:51:02 +00:00
|
|
|
|
2016-06-16 09:16:42 +00:00
|
|
|
@method_decorator(require_POST)
|
2011-09-01 00:51:02 +00:00
|
|
|
def do_sorting_view(self, request, model_type_id=None):
|
|
|
|
|
"""
|
2013-03-11 00:53:05 +00:00
|
|
|
This view sets the ordering of the objects for the model type
|
|
|
|
|
and primary keys passed in. It must be an Ajax POST.
|
2011-09-01 00:51:02 +00:00
|
|
|
"""
|
2016-06-16 09:16:42 +00:00
|
|
|
if not self.has_change_permission(request):
|
|
|
|
|
raise PermissionDenied
|
|
|
|
|
|
Ignore requests with wrong data, e.g. {u'indexes': [u'34,32,35,1,,33,7,5,3,29,27,4,11,14,13,31']}
2013-10-31 12:54:28 +00:00
|
|
|
response = {'objects_sorted': False}
|
|
|
|
|
|
2021-07-16 23:05:59 +00:00
|
|
|
if request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest':
|
2020-05-24 10:07:12 +00:00
|
|
|
klass = ContentType.objects.get(id=model_type_id).model_class()
|
|
|
|
|
|
|
|
|
|
indexes = [str(idx) for idx in request.POST.get('indexes', []).split(',')]
|
|
|
|
|
|
|
|
|
|
# apply any filters via the querystring
|
|
|
|
|
filters = self.get_querystring_filters(request)
|
|
|
|
|
|
|
|
|
|
filters['pk__in'] = indexes
|
2016-06-16 09:16:42 +00:00
|
|
|
|
2020-05-24 10:07:12 +00:00
|
|
|
# Lock rows that we might update
|
|
|
|
|
qs = klass.objects.select_for_update().filter(**filters)
|
2014-09-21 19:12:30 +00:00
|
|
|
|
2020-05-24 10:07:12 +00:00
|
|
|
with transaction.atomic():
|
2021-07-16 23:05:59 +00:00
|
|
|
objects_dict = {str(obj.pk): obj for obj in qs}
|
|
|
|
|
objects_list = [*objects_dict.keys()]
|
2020-05-24 22:58:44 +00:00
|
|
|
if len(indexes) != len(objects_dict):
|
2021-07-16 23:05:59 +00:00
|
|
|
return JsonResponse({
|
2020-05-24 22:58:44 +00:00
|
|
|
'objects_sorted': False,
|
|
|
|
|
'reason': _("An object has been added or removed "
|
|
|
|
|
"since the last load. Please refresh "
|
|
|
|
|
"the page and try reordering again."),
|
2021-07-16 23:05:59 +00:00
|
|
|
}, status_code=400)
|
2015-09-02 13:38:10 +00:00
|
|
|
order_field_name = klass._meta.ordering[0]
|
|
|
|
|
|
2015-10-20 12:11:49 +00:00
|
|
|
if order_field_name.startswith('-'):
|
|
|
|
|
order_field_name = order_field_name[1:]
|
2014-09-21 19:12:30 +00:00
|
|
|
step = -1
|
2020-05-24 22:54:34 +00:00
|
|
|
start_object = objects_dict[objects_list[-1]]
|
|
|
|
|
|
2014-09-21 19:12:30 +00:00
|
|
|
else:
|
|
|
|
|
step = 1
|
2020-05-24 22:54:34 +00:00
|
|
|
start_object = objects_dict[objects_list[0]]
|
2014-09-21 19:12:30 +00:00
|
|
|
|
2015-09-02 13:38:10 +00:00
|
|
|
start_index = getattr(start_object, order_field_name,
|
2015-08-24 02:25:55 +00:00
|
|
|
len(indexes))
|
2020-05-24 10:07:12 +00:00
|
|
|
objects_to_update = []
|
2011-09-01 00:51:02 +00:00
|
|
|
for index in indexes:
|
2011-09-17 21:48:14 +00:00
|
|
|
obj = objects_dict.get(index)
|
2017-03-11 16:20:16 +00:00
|
|
|
# perform the update only if the order field has changed
|
2017-03-09 04:28:40 +00:00
|
|
|
if getattr(obj, order_field_name) != start_index:
|
|
|
|
|
setattr(obj, order_field_name, start_index)
|
2020-05-24 10:07:12 +00:00
|
|
|
objects_to_update.append(obj)
|
2012-03-15 08:58:52 +00:00
|
|
|
start_index += step
|
2020-05-24 10:07:12 +00:00
|
|
|
|
|
|
|
|
qs.bulk_update(objects_to_update, [order_field_name])
|
2012-11-02 13:04:32 +00:00
|
|
|
response = {'objects_sorted': True}
|
Ignore requests with wrong data, e.g. {u'indexes': [u'34,32,35,1,,33,7,5,3,29,27,4,11,14,13,31']}
2013-10-31 12:54:28 +00:00
|
|
|
|
2018-07-09 11:49:55 +00:00
|
|
|
self.after_sorting()
|
|
|
|
|
|
2021-07-16 23:05:59 +00:00
|
|
|
return JsonResponse(response)
|
2011-09-01 00:51:02 +00:00
|
|
|
|
|
|
|
|
|
2014-09-21 19:12:30 +00:00
|
|
|
class NonSortableParentAdmin(SortableAdmin):
|
|
|
|
|
def changelist_view(self, request, extra_context=None):
|
|
|
|
|
return super(SortableAdminBase, self).changelist_view(request,
|
|
|
|
|
extra_context=extra_context)
|
|
|
|
|
|
|
|
|
|
|
2013-04-28 02:58:02 +00:00
|
|
|
class SortableInlineBase(SortableAdminBase, InlineModelAdmin):
|
2011-09-01 00:51:02 +00:00
|
|
|
def __init__(self, *args, **kwargs):
|
2011-09-04 03:02:48 +00:00
|
|
|
super(SortableInlineBase, self).__init__(*args, **kwargs)
|
2011-09-01 00:51:02 +00:00
|
|
|
|
2015-08-24 02:25:55 +00:00
|
|
|
if not issubclass(self.model, SortableMixin):
|
2016-01-12 15:13:15 +00:00
|
|
|
raise Warning(u'Models that are specified in SortableTabularInline'
|
2015-08-24 12:18:22 +00:00
|
|
|
' and SortableStackedInline must inherit from SortableMixin'
|
|
|
|
|
' (or Sortable for legacy implementations)')
|
2011-09-01 00:51:02 +00:00
|
|
|
|
2014-10-06 12:56:41 +00:00
|
|
|
def get_queryset(self, request):
|
2017-03-16 13:44:51 +00:00
|
|
|
qs = super(SortableInlineBase, self).get_queryset(request)
|
2013-04-28 02:58:02 +00:00
|
|
|
if get_is_sortable(qs):
|
|
|
|
|
self.model.is_sortable = True
|
|
|
|
|
else:
|
|
|
|
|
self.model.is_sortable = False
|
|
|
|
|
return qs
|
2011-09-01 00:51:02 +00:00
|
|
|
|
2011-09-04 03:02:48 +00:00
|
|
|
|
2013-05-03 12:35:17 +00:00
|
|
|
class SortableTabularInline(TabularInline, SortableInlineBase):
|
2011-09-04 03:02:48 +00:00
|
|
|
"""Custom template that enables sorting for tabular inlines"""
|
2021-07-16 23:05:59 +00:00
|
|
|
template = 'adminsortable/edit_inline/tabular.html'
|
2011-09-04 03:02:48 +00:00
|
|
|
|
|
|
|
|
|
2013-05-03 12:35:17 +00:00
|
|
|
class SortableStackedInline(StackedInline, SortableInlineBase):
|
2011-09-04 03:02:48 +00:00
|
|
|
"""Custom template that enables sorting for stacked inlines"""
|
2021-07-16 23:05:59 +00:00
|
|
|
template = 'adminsortable/edit_inline/stacked.html'
|
2013-03-15 09:10:01 +00:00
|
|
|
|
|
|
|
|
|
2013-05-03 12:35:17 +00:00
|
|
|
class SortableGenericTabularInline(GenericTabularInline, SortableInlineBase):
|
2013-03-15 09:10:01 +00:00
|
|
|
"""Custom template that enables sorting for tabular inlines"""
|
2021-07-16 23:05:59 +00:00
|
|
|
template = 'adminsortable/edit_inline/tabular.html'
|
2013-03-15 09:10:01 +00:00
|
|
|
|
|
|
|
|
|
2013-05-03 12:35:17 +00:00
|
|
|
class SortableGenericStackedInline(GenericStackedInline, SortableInlineBase):
|
2013-03-15 09:10:01 +00:00
|
|
|
"""Custom template that enables sorting for stacked inlines"""
|
2021-07-16 23:05:59 +00:00
|
|
|
template = 'adminsortable/edit_inline/stacked.html'
|