开发者

Django Formset Iteration go wrong

开发者 https://www.devze.com 2023-03-14 19:00 出处:网络
I am trying to get the cleaned_data for each form in a formset, using a normal iteration (just like what shown in Django documentation):

I am trying to get the cleaned_data for each form in a formset, using a normal iteration (just like what shown in Django documentation):

MyFormSet = formset_factory(form=MyForm, formset=MyBaseFormSet)
my_form_set = MyFormSet(request.POST or None, initial = my_data, prefix = 'myform')

After that I'm validating and trying to iterate through each form and print it values like this:

for f in my_form_set.forms:
    print(f.cleaned_data)

But the result that I get is somekind like this:

<QueryDict: {"myform-0-field_a" : "this is a", "myform-1-field_a" : "this is second a"}>
<QueryDict: {"myform-0-field_a" : "this is a", "myform-1-field_a" : "this is second a"}>

I was expecting to get individual pair of key and values, but instead, for each iteration, I get the 开发者_如何学Gowhole thing of POST data.

I was expecting something like this:

Iteration 0:

"field_a" : "this is a"

Iteration 1:

"field_a" : "this is second a"

Where do I miss?

Thanks


The labels each form field have needs to be unique, otherwise there is no way telling from which form what data came. "myform-0-field_a" , "myform-1-field_a" are the keys/labels The browser send you all fields in one post.

since f.cleaned data seams to be a subclassed dict this will probably work

    for k, v in f.cleaned_data.items():
        print k.split('-')[-1], v

https://docs.djangoproject.com/en/dev/ref/request-response/#querydict-objects

0

精彩评论

暂无评论...
验证码 换一张
取 消