1

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'

2 Answers 2

3

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.
Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

This will throw an AttributeError, as forms don't implement their bound fields as attributes but via item indexing (form['action_name']) and finally the data itself will be in the cleaned_data dict.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.