From 6abd6c598ea23e0a962c87b0075aa2f79f9ead36 Mon Sep 17 00:00:00 2001 From: Jon Dufresne Date: Thu, 1 Dec 2016 18:28:29 -0800 Subject: [PATCH] Fixed #27563 -- Moved "apply limit_choices_to" code from BaseModelForm to fields_for_model(). --- django/forms/models.py | 12 +++++------- tests/model_forms/tests.py | 4 ++++ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/django/forms/models.py b/django/forms/models.py index 3fadc2e3b5..3d74225434 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -170,6 +170,11 @@ def fields_for_model(model, fields=None, exclude=None, widgets=None, formfield = formfield_callback(f, **kwargs) if formfield: + # Apply ``limit_choices_to``. + if hasattr(formfield, 'queryset') and hasattr(formfield, 'get_limit_choices_to'): + limit_choices_to = formfield.get_limit_choices_to() + if limit_choices_to is not None: + formfield.queryset = formfield.queryset.complex_filter(limit_choices_to) field_list.append((f.name, formfield)) else: ignored.append(f.name) @@ -291,13 +296,6 @@ class BaseModelForm(BaseForm): data, files, auto_id, prefix, object_data, error_class, label_suffix, empty_permitted, use_required_attribute=use_required_attribute, ) - # Apply ``limit_choices_to`` to each field. - for field_name in self.fields: - formfield = self.fields[field_name] - if hasattr(formfield, 'queryset') and hasattr(formfield, 'get_limit_choices_to'): - limit_choices_to = formfield.get_limit_choices_to() - if limit_choices_to is not None: - formfield.queryset = formfield.queryset.complex_filter(limit_choices_to) def _get_validation_exclusions(self): """ diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py index d1c5b00d8a..f4216ca51b 100644 --- a/tests/model_forms/tests.py +++ b/tests/model_forms/tests.py @@ -2854,6 +2854,10 @@ class LimitChoicesToTest(TestCase): f = StumpJokeWithCustomFieldForm() self.assertEqual(f.fields['custom'].queryset, 42) + def test_fields_for_model_applies_limit_choices_to(self): + fields = fields_for_model(StumpJoke, ['has_fooled_today']) + self.assertSequenceEqual(fields['has_fooled_today'].queryset, [self.threepwood]) + class FormFieldCallbackTests(SimpleTestCase):