Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access data when form.is_valid() is false

When I have a valid Django form, I can access the data with form.cleaned_data. But how do I get at the data a user entered when the form is not valid i.e., form.is_valid is false.

I'm trying to access forms within a form set, so form.data seems to just give me a mess.

like image 741
Greg Avatar asked Apr 09 '09 19:04

Greg


2 Answers

You can use

form.data['field_name'] 

This way you get the raw value assigned to the field.

like image 133
Dmitry Risenberg Avatar answered Sep 18 '22 13:09

Dmitry Risenberg


See http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation

Secondly, once we have decided that the combined data in the two fields we are considering aren't valid, we must remember to remove them from the cleaned_data.

In fact, Django will currently completely wipe out the cleaned_data dictionary if there are any errors in the form. However, this behaviour may change in the future, so it's not a bad idea to clean up after yourself in the first place.

The original data is always available in request.POST.


A Comment suggests that the point is to do something that sounds like more sophisticated field-level validation.

Each field is given the unvalidated data, and either returns the valid data or raises an exception.

In each field, any kind of validation can be done on the original contents.

like image 24
S.Lott Avatar answered Sep 19 '22 13:09

S.Lott