Initial empty_form value for modelformset_factory

I am trying to add initial values ​​to an empty form formformset_factory.

FormSet = modelformset_factory(MyModel, extra=2) formset = FormSet(queryset=MyModel.objects.none(), initial=[{'foo': 'bar'}, {'foo': 'bar'}]) 

I would like to set the initial value formet.empty_form, how can I achieve this?

+7
django django-forms
source share
2 answers

You can add seed values ​​to your form set as mentioned in this other answer . Then you can set empty_form in the template, for example:

 <form action="/contact/" method="post">{% csrf_token %} {% with formset.empty_form as form %} {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }}: {{ field }} </div> {% endfor %} {% endwith %} <input type="submit" value="Submit" /> </form> 
+1
source share

I'm not sure if this is the right answer, but a quick hack to make this work is to simply re-assign empty_form with the form you want after initializing the form set.

 formset = formset_factory(MyClass, **kwargs) empty = formset.empty_form # empty is a form instance, so you can do whatever you want to it my_empty_form_init(empty_form) formset.empty_form = empty_form 

Note that this overwrites the empty_form property of the resulting set of forms.

0
source share

All Articles