Opened 3 years ago

Last modified 3 years ago

#25880 new Cleanup/optimization

Forms created by formset_factory's extra parameter don't have instance set

Reported by: karyon Owned by: nobody
Component: Forms Version: 1.8
Severity: Normal Keywords:
Cc: johannes.linke@… Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

i have code of the following form:

Model A:
    pass

Model B:
    related_field = ForeignKey(A)


class BForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        print(self.instance.related_field)


def some_view(request):
    InlineBFormset = inlineformset_factory(A, B, formset=ABFormset, form=BForm, extra=1)

    formset = InlineBFormset(request.POST or None, instance=some_a_instance)


the line with the print crashes for the form created by the extra=1 with RelatedObjectDoesNotExist: B has no A. i would have expected that the some_a_instance is set on the form's self.instance.

in django 1.9, i can easily work around that by handing over constructor parameters, but it would still seem weird to me to hand over the related instance that would later be set by the formset's save method anyways.

i can provide the real code if needed.

Change History (2)

comment:1 Changed 3 years ago by karyon

Cc: johannes.linke@… added

comment:2 Changed 3 years ago by Tim Graham

Triage Stage: UnreviewedAccepted
Type: BugCleanup/optimization

Conceptually it seems to make sense, though from a look at the code I couldn't tell if it's feasible. I guess I'll accept the ticket for further investigation. BaseInlineFormSet._construct_form() seems to set the related instance after the form is initialized. If not, maybe it's worth a documentation note?

Note: See TracTickets for help on using tickets.
Back to Top