Reputation: 3928
I try to add initial values to the empty form of a modelformset_factory.
FormSet = modelformset_factory(MyModel, extra=2)
formset = FormSet(queryset=MyModel.objects.none(), initial=[{'foo': 'bar'}, {'foo': 'bar'}])
I would like to set initial value to the formset.empty_form , how can I achieve this ?
Upvotes: 10
Views: 3709
Reputation: 1542
I'm not sure this is the correct answer, but a quick hack to make this work is to simply re-assign empty_form with the form that you want after the formset initialization.
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 does overwrite the empty_form property of the resulting formset.
Upvotes: 0
Reputation: 5212
You can add initial values to your formset as clearly stated in this other answer. Then you're able to set the empty_form
in the template such as:
<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>
Upvotes: 1