diff --git a/adminsortable2/admin.py b/adminsortable2/admin.py index b5f1708..32b6365 100644 --- a/adminsortable2/admin.py +++ b/adminsortable2/admin.py @@ -34,6 +34,7 @@ from django.http import ( HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseForbidden) +from . import encoders __all__ = ['SortableAdminMixin', 'SortableInlineAdminMixin'] @@ -89,6 +90,11 @@ class SortableAdminMixin(SortableAdminBase): BACK, FORWARD, FIRST, LAST, EXACT = range(5) action_form = MovePageActionForm + if encoders.HAS_HASHID: + encoder = encoders.HashidJSONEncoder + else: + encoder = DjangoJSONEncoder + @property def change_list_template(self): opts = self.model._meta @@ -244,7 +250,7 @@ def update_order(self, request): startorder = int(request.POST.get('startorder')) endorder = int(request.POST.get('endorder', 0)) moved_items = list(self._move_item(request, startorder, endorder)) - return HttpResponse(json.dumps(moved_items, cls=DjangoJSONEncoder), content_type='application/json;charset=UTF-8') + return HttpResponse(json.dumps(moved_items, cls=self.encoder), content_type='application/json;charset=UTF-8') def save_model(self, request, obj, form, change): if not change: diff --git a/adminsortable2/encoders.py b/adminsortable2/encoders.py new file mode 100644 index 0000000..1bc2e59 --- /dev/null +++ b/adminsortable2/encoders.py @@ -0,0 +1,14 @@ +from django.core.serializers.json import DjangoJSONEncoder + +try: + from hashid_field import Hashid + HAS_HASHID = True +except ImportError: + HAS_HASHID = False + pass + +class HashidJSONEncoder(DjangoJSONEncoder): + def default(self, o): + if isinstance(o, Hashid): + return str(o) + return super().default(o)