10

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 ?

sam
  • 3,498
  • 3
  • 22
  • 19
  • Sorry, the question doesn't really make sense. What is wrong with the code you have posted? Do you get an error - if so, what? Does it not have the desired effect - if so, what is the desired effect and what actually happens? – Daniel Roseman Jul 09 '10 at 13:44
  • 3
    You are right, my code works fine, but I would like a way to set initial value, not to my 2 extra forms (like in my example), but to the empty_form (in formset.empty_form) – sam Jul 09 '10 at 13:52
  • @sam have you solved the problem? – MatheusJardimB Mar 05 '15 at 17:26

2 Answers2

1

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>
Community
  • 1
  • 1
vascop
  • 4,972
  • 4
  • 37
  • 50
0

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.

Jkk.jonah
  • 1,502
  • 1
  • 11
  • 16