3

In Django formsets (v. 1.9), there is an option min_num in the formset_factory function which specifies the minimum number of forms in the formset.

A view might look like this:

class ExampleForm(forms.Form):
    msg = forms.CharField()

ExFormSet = formset_factory(ExampleForm, min_num=1)
ex_set =  ExFormSet()

context = {'ex_set': exp_set)
return render(request, 'app-name/test.html', context)

And the template might look like this:

<form action="" method="post">
  <table>
    {{ ex_set }}
  </table>
</form>

However Django will always render one more form then given in the min_num argument.

Is the reason for this the general Django/Python design, starting to count at zero or am I misunderstanding the use of the min_num argument? In the docs as I understand it, it says that the variable is just used for validation.

Jarno
  • 6,243
  • 3
  • 42
  • 57
  • 1
    I presume its a typo in your question but in your context you set `ex_set` in the context to `exp_set` that isn't mentioned anywhere else – Sayse Apr 13 '16 at 15:04

1 Answers1

4

One more form is from extra keyword parameter whose default value is 1. You can read here for more info on extra keyword parameter.

mehmet
  • 7,720
  • 5
  • 42
  • 48
Muhammad Tahir
  • 5,006
  • 1
  • 19
  • 36
  • Yes I also found, that `extra` overrides the `min_num` parameter, in the sense that it determines the number of empty forms displayed at the beginning. But why does `min_num` show this behaviour if `extra` argument is not given? – Jarno Apr 13 '16 at 15:20
  • @Jarno because `extra` have a default value of `1`, which is used if you do not pass it explicitly, try passing `extra=0` explicitly. – Muhammad Tahir Apr 13 '16 at 15:21
  • It seems that the number of number of empty forms is determined by `extra + minum`. E.g. if I pass `form_factory()` `extra=-2, min_num=5`, I get 3 empty forms. Still I don't understand the sense of two arguments that affect the same parameter. – Jarno Apr 13 '16 at 15:42
  • 1
    Both serve different purposes, you are experimenting with empty forms, that is why you are being confused, you will understand if you experiment with editing existing instances using formset. `min_num` is for validation purposes, when formset is submitted to server it must have `min_num` forms in it. `extra` specifies how many extra forms should be created to create new instances of data along with existing instances you are editing. So if you do `MyFormSet(reques.POST['data of 5 objects'], extra=2)`, it will create 7 forms, 2 to create new objects, 5 to edit older. – Muhammad Tahir Apr 13 '16 at 15:50