Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed #22046 -- Unhelpful queryset handling for model formsets with data... #2277

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion django/forms/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -593,9 +593,29 @@ def _construct_form(self, i, **kwargs):
pass
return super(BaseModelFormSet, self)._construct_form(i, **kwargs)

def _get_data_pks(self):
"""Returns a list of all the pks in the form data."""
pks = []
pk_field = self.model._meta.pk
to_python = self._get_to_python(pk_field)
for i in range(self.initial_form_count()):
pk_key = "%s-%s" % (self.add_prefix(i), pk_field.name)
pk = self.data[pk_key]
pks.append(to_python(pk))
return pks

def get_queryset(self):
if not hasattr(self, '_queryset'):
if self.queryset is not None:
if self.is_bound:
# Bound forms must only deal with the instances
# specified by the data. Allowing any other filters
# could cause the data specified instances to not be
# found.
qs = self.model._default_manager.get_queryset()
qs = qs.filter(**{
self.model._meta.pk.name+'__in': self._get_data_pks(),
})
elif self.queryset is not None:
qs = self.queryset
else:
qs = self.model._default_manager.get_queryset()
Expand Down
41 changes: 41 additions & 0 deletions tests/model_formsets/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1183,6 +1183,47 @@ def test_model_formset_with_initial_queryset(self):
formset = FormSet(initial=[{'authors': Author.objects.all()}], data=data)
self.assertFalse(formset.extra_forms[0].has_changed())

def test_model_formset_with_mismatched_queryset(self):
FormSet = modelformset_factory(Author, fields=('name', ))
Author.objects.create(pk=10, name='Charles Baudelaire')
Author.objects.create(pk=20, name='Arthur Rimbaud')
data = {
'form-TOTAL_FORMS': 1,
'form-INITIAL_FORMS': 1,
'form-MAX_NUM_FORMS': 1,
'form-0-id': '20',
'form-0-name': 'A. Rimbaud',
}
formset = FormSet(data=data, queryset=Author.objects.filter(pk=10))
formset.save()

self.assertEqual(
set(Author.objects.values_list('pk', 'name')),
set([
(10, 'Charles Baudelaire'),
(20, 'A. Rimbaud'),
]),
)

def test_model_formset_limits_queryset_to_data(self):
FormSet = modelformset_factory(Author, fields=('name', ))
Author.objects.create(pk=10, name='Charles Baudelaire')
Author.objects.create(pk=20, name='Arthur Rimbaud')
data = {
'form-TOTAL_FORMS': 1,
'form-INITIAL_FORMS': 1,
'form-MAX_NUM_FORMS': 1,
'form-0-id': '20',
'form-0-name': 'A. Rimbaud',
}
formset = FormSet(data=data, queryset=Author.objects.filter(pk=10))
self.assertEqual(
set(formset.get_queryset().values_list('pk', 'name')),
set([
(20, 'Arthur Rimbaud'),
]),
)

def test_prevent_duplicates_from_with_the_same_formset(self):
FormSet = modelformset_factory(Product, fields="__all__", extra=2)
data = {
Expand Down