From 3cb63b0e473568cb5158d7a4f13cb7e1c9ee89f5 Mon Sep 17 00:00:00 2001 From: Tim Graham Date: Thu, 14 Apr 2016 09:10:33 -0400 Subject: [PATCH] Refs #26502 -- Added choices to Form.__getitem__() KeyError message. --- django/forms/forms.py | 7 ++++++- tests/forms_tests/tests/test_forms.py | 5 ++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/django/forms/forms.py b/django/forms/forms.py index df382deda9..ac5cf12425 100644 --- a/django/forms/forms.py +++ b/django/forms/forms.py @@ -140,7 +140,12 @@ class BaseForm(object): field = self.fields[name] except KeyError: raise KeyError( - "Key %r not found in '%s'" % (name, self.__class__.__name__)) + "Key '%s' not found in '%s'. Choices are: %s." % ( + name, + self.__class__.__name__, + ', '.join(sorted(f for f in self.fields)), + ) + ) if name not in self._bound_fields_cache: self._bound_fields_cache[name] = field.get_bound_field(self, name) return self._bound_fields_cache[name] diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py index a8bff32a8c..a5d8fbebdb 100644 --- a/tests/forms_tests/tests/test_forms.py +++ b/tests/forms_tests/tests/test_forms.py @@ -71,10 +71,9 @@ class FormsTestCase(SimpleTestCase): '' ) - nonexistenterror = "Key u?'nonexistentfield' not found in 'Person'" - with six.assertRaisesRegex(self, KeyError, nonexistenterror): + msg = "Key 'nonexistentfield' not found in 'Person'. Choices are: birthday, first_name, last_name." + with self.assertRaisesMessage(KeyError, msg): p['nonexistentfield'] - self.fail('Attempts to access non-existent fields should fail.') form_output = []