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.

Community
  • 1
  • 1
Brant
  • 5,721
  • 4
  • 36
  • 39

1 Answers1

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.

Brant
  • 5,721
  • 4
  • 36
  • 39
  • That's great thanks! But how do you prevent the post data from being validated? – Greg Apr 19 '11 at 17:51
  • As I understand it, the validation happens automatically as part of the forms.Form/forms.ModelForm system... – Brant Apr 20 '11 at 11:42
  • 1
    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. – Greg Apr 20 '11 at 12:56
  • 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. – Brant Apr 21 '11 at 12:16
  • 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. – vdboor Apr 22 '12 at 21:16
  • It maybe because of this solution, I add a form using this technique, later on havent changed a thing, I want to delete this row, I get form invalid message. anybody with same outcome? – durdenk Aug 28 '16 at 23:25
  • It's easy to suppress the validation messages of the form by setting `_errors = {}`. See https://stackoverflow.com/questions/64402527/ – medihack Oct 18 '20 at 20:02