1
0
mirror of https://github.com/django/django.git synced 2024-12-22 17:16:24 +00:00

Fixed #22828 -- Warned that ModelAdmin get hooks return the property itself rather a copy.

This commit is contained in:
koresi 2024-09-25 03:57:20 +02:00 committed by Sarah Boyce
parent ef28b05767
commit b8e9cdf13b

View File

@ -1465,6 +1465,27 @@ templates used by the :class:`ModelAdmin` views:
See also :ref:`saving-objects-in-the-formset`.
.. warning::
All hooks that return a ``ModelAdmin`` property return the property itself
rather than a copy of its value. Dynamically modifying the value can lead
to surprising results.
Let's take :meth:`ModelAdmin.get_readonly_fields` as an example::
class PersonAdmin(admin.ModelAdmin):
readonly_fields = ["name"]
def get_readonly_fields(self, request, obj=None):
readonly = super().get_readonly_fields(request, obj)
if not request.user.is_superuser:
readonly.append("age") # Edits the class attribute.
return readonly
This results in ``readonly_fields`` becoming
``["name", "age", "age", ...]``, even for a superuser, as ``"age"`` is added
each time non-superuser visits the page.
.. method:: ModelAdmin.get_ordering(request)
The ``get_ordering`` method takes a ``request`` as parameter and