Getting Data From a Bound but Unvalidated Form

I have a form with dynamic fields, meaning the answers available for field B depend on the answer for field A.  Therefore, when the form is submitted I get the value from field B, but when it's redisplayed I have to read the value from field A and populate the choices for field B or else field B is blanked out in the browser. I looked for a convenient way to read the bound data from a specified form field and was surprised that I couldn't find one.  I could just read the POST, but this form is in a formset with a prefix, so I'd have to assemble a complicated key name like “foo_bar_form-1-fieldname”.  The closest I saw to an interface to get the data was the _raw_value(fieldname) method which I couldn't get to work and is suboptimal since it's an internal call and could change in the future. I ended up having to go to the POST data anyway, but I saw a helper function in _raw_value(fieldname) that made it easier.  What I ended up doing was this:

field_value = self.request.POST[form.add_prefix('fieldname')]

add_prefix(fieldname) is a public method to take care of the prefix hassle for me, so reading the post value is doable.  The only thing to watch out for is that you have to handle potential invalid values when redisplaying a form with errors.


Cezar: Do you mean unbound data?

Cezar: I guess my question is. How do you have bound data that's not validated? I thought is_valid() is what bound it?

tsaylor: The data is bound when you instantiate the form with a dictionary in the first parameter. At that point the data can be found in, and validating moves it to form.cleaned_data.