Rui Xia
Rui Xia

Reputation: 175

how to access form's data in a django formset

I have problem on accessing the form data from a formset. I attached the code:

####FORM
class ActionTypeForm(forms.Form):
     action_name = models.CharField(max_length=20)
     description = models.CharField(max_length=250, blank=True, null=True)


####VIEW
dataset = request.POST
ActionTypeFormSet = formset_factory(ActionTypeForm)
formset = ActionTypeFormSet(dataset)

if formset.is_valid():
     for form in formset.cleaned_data:  #I ALSO TESETED formset.forms
           customer.create_actiontype(form['action_name'], form['description'])

the error is I can't get form['action_name']. formset.is_valid() return True

ERROR

Exception Type: KeyError

Exception Value: 'action_name'

POST DATA

form-0-action_name u'a'

form-2-description u'sadsa'

form-0-description u'a'

form-MAX_NUM_FORMS u''

form-1-description u'asd'

form-TOTAL_FORMS u'3'

form-1-action_name u'as'

form-INITIAL_FORMS u'0'

csrfmiddlewaretoken u'c4fa9ddb4ec69ac639d7801eb14979f2'

form-2-action_name u'asda'

Upvotes: 1

Views: 4929

Answers (2)

Filip Dupanović
Filip Dupanović

Reputation: 33660

The formset stores all it's associated forms in self.forms and iterating over it will return an iterator iter(self.forms) for the forms.

Your POST data looks good, so this is how you can make it work:

if formset.is_valid():
    for form in formset: 
        customer.create_actiontype(form.action_name, form.description)

Upvotes: 0

The main problem is that you have a blank form. You are using model fields in your form class definition, which django's forms framework has no idea what to do with. Django models != django forms.

The formset is validating and returning empty forms which of course have no form fields.

You should either create Formsets out of forms with valid form fields, or ModelFormsets out of Models.

  • Update: I initially thought that formsets don't have cleaned_data, but I guess they do return a list of cleaned_datas of all forms, which means the problem with your code is just the above.

Upvotes: 3

Related Questions