django-admin-sortable2
django-admin-sortable2 copied to clipboard
SortableInlineAdminMixin with reverse ordering and new objects on top of the list
I am trying to develop an TabularInline admin class which uses the SortableInlineAdminMixin to sort the objects via drag and drop. I also want that, when I create a new object, it gets on top of the drag and drop list.
At first, I tried using a field order = models.IntegerField(default=0) and ordering = ['-order'] inside the Meta class of my model class. So, let's say I have 3 items, A (order=1), B(order=2) and C(order=3). As the ordering is -order, they are displayed in the admin section as follows: C, B, A.
When I add a new item D and save it, it gets the order value 4, so it is displayed on top of the list: D, C, B, A. Until this point, everything works as expected.
Now let's say I drag element A to the second position of the inverse list. Before saving, I'd have D(order=4), A(order=1), C(order=3) and B(order=2). But, after saving, all the order values are reversed and I get: B(order=4), C(order=3), A(order_2), D(order_1), instead of D,A,C,B, that would be what I expected.
What would be the best solution to get this? Is there maybe any other workaround I am missing? I would kindly appreciate any help :)
In your admin.py, I would create a class inheriting from CustomInlineFormSet. Refer to that class
with:
class MyInlineModelAdmin(SortableInlineAdminMixin, admin.TabularInline):
formset = MyCustomInlineFormSet
...
Then override method save_new. Inside use super().save_new(form, commit=False) to call the base method. Afterwards move the new element to the first position using _move_item or do the ordering yourself.
is my proposal a solution? Can this issue be closed
I think this can be closed indeed.