Skip to content

Commit 893d265

Browse files
committed
Fixed 2259 -- Made manually defined PKs readonly in admin inlines.
1 parent 25fae5e commit 893d265

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

django/contrib/admin/options.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,20 @@ def get_ordering(self, request):
414414
"""
415415
return self.ordering or () # otherwise we might try to *None, which is bad ;)
416416

417+
def _get_readonly_manual_pk_fields(self, obj):
418+
"""
419+
Returns a list containing the primary key field name if:
420+
- we're editing an existing object,
421+
- the PK was manually defined (not auto-created),
422+
- and it's not already in self.readonly_fields.
423+
"""
424+
if not obj:
425+
return []
426+
pk = self.model._meta.pk
427+
if pk.editable and not pk.auto_created and pk.name not in self.readonly_fields:
428+
return [pk.name]
429+
return []
430+
417431
def get_readonly_fields(self, request, obj=None):
418432
"""
419433
Hook for specifying custom readonly fields.

django/contrib/admin/static/admin/css/base.css

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -109,10 +109,6 @@ body {
109109
background: var(--body-bg);
110110
}
111111

112-
label {
113-
font-size: 1rem;
114-
}
115-
116112
/* LINKS */
117113

118114
a:link, a:visited {

tests/admin_inlines/tests.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
Child,
2020
ChildModel1,
2121
ChildModel2,
22+
EditablePKBook,
2223
ExtraTerrestrial,
2324
Fashionista,
2425
FootNote,
@@ -708,6 +709,21 @@ def test_inline_editable_pk(self):
708709
count=1,
709710
)
710711

712+
def test_inline_manual_pk_is_readonly_when_editing(self):
713+
author = Author.objects.create(name="Jane Austen")
714+
EditablePKBook.objects.create(
715+
author=author, manual_pk=101, title="Pride and Prejudice"
716+
)
717+
718+
response = self.client.get(
719+
reverse("admin:admin_inlines_author_change", args=[author.pk])
720+
)
721+
722+
self.assertContains(
723+
response, 'name="editablepkbook_set-0-manual_pk"', html=False
724+
)
725+
self.assertContains(response, "readonly", html=False)
726+
711727
def test_stacked_inline_edit_form_contains_has_original_class(self):
712728
holder = Holder.objects.create(dummy=1)
713729
holder.inner_set.create(dummy=1)

0 commit comments

Comments
 (0)