2

I am trying to create records using an inline formSet while at the same time creating a record with a normal form whose primary key is the foreign key for the inline formSet all on the same HTML page.

Make sense? Here's what I mean: Suppose I have the following two models (not real code, obviously, but you get the idea):

Class mainModel
    Primary Key (custom pk I create)
    field1
    field2

Class inlineFormModel
    autoPK
    field1 = ForeignKey(mainModel)
    field2

Now, I want to create a single HTML page for the user so they can create a mainModel instance at the same time as creating a number of inlineFormModel instances. The mainModel would be a normal form while the inlineFormModel would be using inlineFormsets. The problem is that when I save all the forms, there is no foreignKey to link to the inline formSet records since the model it refers to is still be created (everything gets saved in the same view). Does that make sense?

How would I go about creating a new mainModel instance with several secondModel instances and save the whole batch all with the same view function?

Thanks!

1 Answer 1

3

This is a common scenario, I do not know why is not addressed in the docs:

    initial_form = mainModelForm(request.POST)
    if initial_form.is_valid():
        form= initial_form.save(commit=False)
        my_formset = inline_formset(request.POST,instance=form)
        if my_formset.is_valid():
           form.save()
           my_formset.save()
.......  .........
# return codes here
Sign up to request clarification or add additional context in comments.

2 Comments

Does it matter if I have 3 inline_formsets all of which have the same initial_form's PK as a Foreign Key?
so in this case, both the initial form and the formset are rendered inside the same <form> such that all data from both is submitted and defined in request?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.