Reputation: 61
I am using two forms on one page (I have my reasons). They are not model forms. I am trying to validate them by using prefix. I found it here: Proper way to handle multiple forms on one page in Django But when I try to get cleaned_data, i get key error. Here is some of my code:
add_form = AbsenceTypeForm(request.POST, prefix = 'atype')
if add_form.is_valid():
absence_type = AbsenceType(
client = client_instance,
name = add_form.cleaned_data['type_name'],
gainful = add_form.cleaned_data['gainful'],
)
absence_type.save()
And I get KeyError for type_name. I tried to add cleaned_data['atype-type_name']
- nothing helps.
Upvotes: 2
Views: 2418
Reputation: 449
What about dumping the cleaned_data somewhere, to a screen or a file - just to check the keys it gets? Debugger should also show the dictionary in the locals. I would guess it's either lost / misspelled prefix or the form field name.
Btw I agree that using .get() is safer (even though it looks like the form validation should be already handled by is_valid(), however you might decide to change the field to be non-mandatory in the future and then this code would error), so:
name = add_form.cleaned_data.get('type_name',None),
gainful = add_form.cleaned_data.get('gainful',None),
if name and gainful:
pass
#rest of the code
Upvotes: 2
Reputation: 1026
Maybe you left type_name
empty in your posted form; cleaned_data
only contains keys for non-empty form fields.
Upvotes: 0