Skip to content

Admin inline saving triggers exception when model has order_with_respect_toΒ #339

@a-ruban

Description

@a-ruban

πŸ” Problem

In admin inlines, Django instantiates model instances with default field values β€” this means that the order_with_respect_to field is initially None, and only later gets set during the form processing or saving.

However, OrderedModel.__init__() captures the _original_wrt_map() at instantiation time, so when the field is later set to a proper object, wrt_changed becomes True, triggering while saving:

  • Decreasing order in the old (empty) context
  • Reordering in the new one
  • In some admin workflows, this manifests as a delete-and-recreate cycle

This happens even though the object is new and never had a valid wrt value before.

Workaround:

    def get_formset(self, request, obj=None, **kwargs):
        formset_class = super().get_formset(request, obj, **kwargs)

        class PatchedFormset(formset_class):
            def _construct_form(self, i, **kwargs):
                form = super()._construct_form(i, **kwargs)
                if self.instance:
                    form.instance.*order_with_respect_to* = self.instance
                    if hasattr(form.instance, '_original_wrt_map'):
                        form.instance._original_wrt_map = form.instance._wrt_map()
                return form

        return PatchedFormset

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions