2

I have an edit object view that contains a formset(one or many if this matters), now I want to create a page that can display multiple edit object forms and submit it in a single form.

What is the correct way to achieve this task?

2

1 Answer 1

4

I found a solution.

I can enumerate my objects on edit page and use different prefixes for formsets based on these indexes. Here is an example:

First, you need enumeration, I achieved it using same input(checkbox) name with incremental values:

<input type="checkbox" name="counter" value="0">
...
<input type="checkbox" name="counter" value="1">
...

Counter numbers is the formset and other data serial numbers:

<!--Ordinary inputs-->
<input type="text" name="data0" value="value0">
<input type="text" name="data1" value="value1">
<!--Formsets-->
<input type="text" id="test0-0-data" name="test0-0-data" value="something">
<input type="text" id="test0-1-data" name="test0-1-data" value="something">
<input type="hidden" name="test0-TOTAL_FORMS" id="id_test0-TOTAL_FORMS" value="2">
<input type="hidden" name="test0-INITIAL_FORMS" id="id_test0-INITIAL_FORMS" value="0">

<input type="text" id="test1-0-data" name="test1-0-data" value="something">
<input type="hidden" name="test1-TOTAL_FORMS" id="id_test1-TOTAL_FORMS" value="1">
<input type="hidden" name="test1-INITIAL_FORMS" id="id_test1-INITIAL_FORMS" value="0">

Then if code you populate formsets like this:

counter = request.POST.getlist('counter')
for i in counter:
    TestFormset = modelformset_factory(Test, form=TestForm)
    test_formset = TestFormset(request.POST, prefix='test'+i, queryset=Test.objects.none())

I achieved HTML structure above with JavaScript.

Sign up to request clarification or add additional context in comments.

1 Comment

Could you elaborate a bit more for a django newbie?

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.