From a8adb6aa6cc6b9efd043acc980b5744bc211c760 Mon Sep 17 00:00:00 2001 From: Prashant Pandey Date: Thu, 23 Nov 2023 10:29:52 +0530 Subject: [PATCH] Fixed #26827 -- Improved ModelState error message when relations refer model classes. --- AUTHORS | 1 + django/db/migrations/state.py | 10 ++++++---- tests/migrations/test_state.py | 8 ++++---- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/AUTHORS b/AUTHORS index 0247503197da..f63f712f3a41 100644 --- a/AUTHORS +++ b/AUTHORS @@ -816,6 +816,7 @@ answer newbie questions, and generally made Django that much better: plisk polpak@yahoo.com pradeep.gowda@gmail.com + Prashant Pandey Preston Holmes Preston Timmons Priyank Panchal diff --git a/django/db/migrations/state.py b/django/db/migrations/state.py index 4aa6e1f6cc64..5ffd7fc07a74 100644 --- a/django/db/migrations/state.py +++ b/django/db/migrations/state.py @@ -738,13 +738,15 @@ def __init__( # Sanity-check that relation fields are NOT referring to a model class. if field.is_relation and hasattr(field.related_model, "_meta"): raise ValueError( - 'ModelState.fields cannot refer to a model class - "%s.to" does. ' - "Use a string reference instead." % name + 'Model fields in "ModelState.fields" cannot refer to a model class ' + f'- "{self.app_label}.{self.name}.{name}.to" does. Use a string ' + "reference instead." ) if field.many_to_many and hasattr(field.remote_field.through, "_meta"): raise ValueError( - 'ModelState.fields cannot refer to a model class - "%s.through" ' - "does. Use a string reference instead." % name + 'Model fields in "ModelState.fields" cannot refer to a model class ' + f'- "{self.app_label}.{self.name}.{name}.through" does. Use a ' + "string reference instead." ) # Sanity-check that indexes have their name set. for index in self.options["indexes"]: diff --git a/tests/migrations/test_state.py b/tests/migrations/test_state.py index f1ac78c9926e..686eba450038 100644 --- a/tests/migrations/test_state.py +++ b/tests/migrations/test_state.py @@ -1651,8 +1651,8 @@ def test_sanity_check_to(self): field = models.ForeignKey(UnicodeModel, models.CASCADE) with self.assertRaisesMessage( ValueError, - 'ModelState.fields cannot refer to a model class - "field.to" does. ' - "Use a string reference instead.", + 'Model fields in "ModelState.fields" cannot refer to a model class - ' + '"app.Model.field.to" does. Use a string reference instead.', ): ModelState("app", "Model", [("field", field)]) @@ -1661,8 +1661,8 @@ def test_sanity_check_through(self): field.remote_field.through = UnicodeModel with self.assertRaisesMessage( ValueError, - 'ModelState.fields cannot refer to a model class - "field.through" does. ' - "Use a string reference instead.", + 'Model fields in "ModelState.fields" cannot refer to a model class - ' + '"app.Model.field.through" does. Use a string reference instead.', ): ModelState("app", "Model", [("field", field)])