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’
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, orModelFormsets out ofModels.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.