id summary reporter owner description type status component version severity resolution keywords cc stage has_patch needs_docs needs_tests needs_better_patch easy ui_ux 27416 ModelFormSet with queryset accepts invalid POST data for outer models and create unexpected empty data. Hiroki Kiyohara Hiroki Kiyohara "ModelFormSet with queryset argument will accept invalid POST data and create unexpected empty data. Invalid data means that data won't be appear in `queryset=...`, like this. {{{#!python author = Author.objects.create(pk=1, name='Walt Whitman') other_author = Author.objects.create(pk=2, name='Charles Baudelaire') AuthorFormSet = modelformset_factory(Author, fields=""__all__"", extra=0) data = { 'form-TOTAL_FORMS': '2', # the number of forms rendered 'form-INITIAL_FORMS': '2', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(author.id), 'form-0-name': 'Walt Whitman', 'form-1-id': str(other_author.id), # Specifying outer model of bellow queryset. 'form-1-name': 'Changed name', } # This formset is only for Walt Whitman # and should not accept POST data for other_author formset = AuthorFormSet(data=data, queryset=Author.objects.filter(id__in=(author.id,))) }}} This formset should ignore unexpected `form-1-id': str(other_author.id)` value, a value not in queryset. The value in `other_author` won't be changed, but this formset will create unexpected new **empty data** (which has `Author.name = """"`). === Why Internally... 1. In Formsets, forms corresponding to invalid data will be instantiated with `instance=None` (due to this line https://github.com/django/django/blob/master/django/forms/models.py#L597) 2. ModelForm will set form.instance as empty instance (`self.instance = opts.model()`) 3. Saving `formset.save()` will save this unexpected invalid data === Why it's problem It will create unexpected empty data and may cause IntegrityError. For instance, if Artist.name field has unique constraint, and invalid POST data come sometimes, it will create empty Artist data more than twice and cause UNIQUE constraint error. === PS Is this recognized as bug? or should I specify more extra args for formset? I searched similar tickets but not existed. (Just ticket I found is #26142 to prevent to create new instance for FormSet, It may prevent this problem too but not correct way to solve)." Bug closed Forms 1.10 Normal fixed formset,modelform Ready for checkin 1 0 0 0 0 0