6

This post relates to this: Add row to inlines dynamically in django admin

Is there a way to achive adding inline formsets WITHOUT using javascript? Obviously, there would be a page-refresh involved.

So, if the form had a button called 'add'...

I figured I could do it like this:

if request.method=='POST':
  if 'add' in request.POST:
    PrimaryFunctionFormSet = inlineformset_factory(Position,Function,extra=1)
    prims = PrimaryFunctionFormSet(request.POST)

Which I thought would add 1 each time, then populate the form with the post data. However, it seems that the extra=1 does not add 1 to the post data.

1 Answer 1

6

Got it.

Sometimes it's the simplest solution. Just make a copy of the request.POST data and modify the TOTAL-FORMS.

for example..

if request.method=='POST':
  PrimaryFunctionFormSet = inlineformset_factory(Position,Function)
  if 'add' in request.POST:
    cp = request.POST.copy()
    cp['prim-TOTAL_FORMS'] = int(cp['prim-TOTAL_FORMS'])+ 1
    prims = PrimaryFunctionFormSet(cp,prefix='prim')

Then just spit the form out as normal. Keeps your data, adds an inline editor.

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

7 Comments

That's great thanks! But how do you prevent the post data from being validated?
As I understand it, the validation happens automatically as part of the forms.Form/forms.ModelForm system...
So that didn't matter for your purposes? I'm thinking if a user has entered data in one row and requests another, they wouldn't want any validation to happen until they submit. I'll check in Django if I can turn it off.
Ah. yea, I see what you are asking now. Yes, the validation still occurs and throws the "this field is required" errors but the next inline formset still gets added during the process. I've found that it works out just fine... plus it lets the user know which fields they will need to fill in, once they actually submit.
You might be able to skip the validation by passing the POST values in the 'initial' parameter. This needs a conversion to list of dicts though.
|

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.