I am running into an annoying problem when trying to create formsets
dynamically.
I have a script that sends JSON data to a view to render it as a
formset. The response is then inserted in the page:
Script:
data = JSON.stringify([1, 2, 3]);
$("#container").load("render-form/", {data: data});
View:
def render_form(request):
data = simplejson.loads(request.POST["data"])
objs = [SomeModel(i) for i in data]
FormSet = modelformset_factory(SomeModel, extra=0)
forms = FormSet(queryset=objs)
return render_to_response("form_template.html", {"forms": forms})
It works but I get incorrect ManagementForm data in the output:
<input id="id_somemodel-TOTAL_FORMS" type="hidden" value="3"
name="attendee-TOTAL_FORMS"/>
<input id="id_somemodel-INITIAL_FORMS" type="hidden" value="3"
name="attendee-TOTAL_FORMS"/>
For django to save the formset correctly when it is submitted, I have to
manually set INITIAL_FORMS to 0 in javascript (because the objects are
not really in the database).
I tried to create the formset using extra=3 and passing the data via the
'initial' argument, but this gives an IndexError (django is trying to
set the forms 'instance' attribute from the queryset, but it is empty).
Is there a less hackish way to do this ?
It looks like you are trying to shove a square object through a round
hole. Why are you using a model formset when there is "real" queryset?
Model formsets are simply a thin layer over formsets. It sounds like
you need to those to cleanly write your code and not resort to hacking
a model formset to work without a real queryset.
--
Brian Rosner
http://oebfare.com
Ugh. That didn't read as well as I hoped :)
I meant to ask, why are you using model formsets when there is no
"real" queryset? You should just use formsets.
That file is not just model formset code. In terms of what a model
formset does, it is thin. It doesn't not change any behavior of a
regular formset. Just provides the additional layer to hook up with
models. I still consider that thin ;)
>
> I use it because I want to write forms that save models, and avoid
> duplicating my model structure in the form class. Is'nt it what
> modelforms are meant for ?
Then why are you not able to pass in a queryset? What data are you
sending to the server to generate the formset? From the little
explained code are they just primary keys?
I think from what I gather you are looking to create an "add"-only
model formset? If so take a look at
http://code.djangoproject.com/ticket/9538. I have written some
information on that ticket that may be of use to you.
Can you file a ticket about this? The fundamental issue here is that
formsets use initial data to populate the forms, but model formsets
make no distinction between initial data being passed in and initial
data it makes via the queryset. It sounds worth fixing.