From 119f227aa62885f12cd7dd2558a62148d02adbb4 Mon Sep 17 00:00:00 2001 From: Hrushikesh Vaidya Date: Sun, 27 Feb 2022 08:26:16 +0530 Subject: [PATCH] Fixed #33524 -- Allowed overriding empty_label for ForeignKey in ModelAdmin.radio_fields. --- django/contrib/admin/options.py | 4 +++- tests/admin_widgets/tests.py | 12 ++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py index 64be087bf1..63f5cb2b27 100644 --- a/django/contrib/admin/options.py +++ b/django/contrib/admin/options.py @@ -269,7 +269,9 @@ class BaseModelAdmin(metaclass=forms.MediaDefiningClass): "class": get_ul_class(self.radio_fields[db_field.name]), } ) - kwargs["empty_label"] = _("None") if db_field.blank else None + kwargs["empty_label"] = ( + kwargs.get("empty_label", _("None")) if db_field.blank else None + ) if "queryset" not in kwargs: queryset = self.get_field_queryset(db, db_field, request) diff --git a/tests/admin_widgets/tests.py b/tests/admin_widgets/tests.py index db724b4196..cce759a9c8 100644 --- a/tests/admin_widgets/tests.py +++ b/tests/admin_widgets/tests.py @@ -21,6 +21,7 @@ from django.db.models import ( CharField, DateField, DateTimeField, + ForeignKey, ManyToManyField, UUIDField, ) @@ -141,6 +142,17 @@ class AdminFormfieldForDBFieldTests(SimpleTestCase): ) self.assertIsNone(ff.empty_label) + def test_radio_fields_foreignkey_formfield_overrides_empty_label(self): + class MyModelAdmin(admin.ModelAdmin): + radio_fields = {"parent": admin.VERTICAL} + formfield_overrides = { + ForeignKey: {"empty_label": "Custom empty label"}, + } + + ma = MyModelAdmin(Inventory, admin.site) + ff = ma.formfield_for_dbfield(Inventory._meta.get_field("parent"), request=None) + self.assertEqual(ff.empty_label, "Custom empty label") + def test_many_to_many(self): self.assertFormfield(Band, "members", forms.SelectMultiple)