2

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.

Community
  • 1
  • 1
Kroitus
  • 61
  • 1
  • 6

2 Answers2

2

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
Damian
  • 449
  • 5
  • 11
0

Maybe you left type_name empty in your posted form; cleaned_data only contains keys for non-empty form fields.

Webthusiast
  • 827
  • 8
  • 16