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.
You access the data from either the field's clean() method, or from the form's clean() method. clean() is the function that determines whether the form is valid or not. It's called when is_valid() is called. In form's clean() you have the
cleaned_data
list when you can run through custom code to make sure it's all checked out. In the widget, you have a clean() also, but it uses a single passed variable. In order to access the field's clean() method, you'll have to subclass it. e.g.:If you want an IntField that doesn't choke on an empty value, for instance, you'd use the above.
clean() on a form kind of works like this:
Also you can have a clean_FIELD() function for each field so you can validate each field individually (after the field's clean() is called)
You can use
This way you get the raw value assigned to the field.
You can use this pattern:
In your code:
Using form.data is not a good solution. Reasons:
See http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation
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.
I was struggling with a similar issue, and came across a great discussion here: https://code.djangoproject.com/ticket/10427
It's not at all well documented, but for a live form, you can view a field's value -- as seen by widgets/users -- with the following:
I have many methods. All you can pick.
I suppose the form is like as below:
1-1. Get from
request
2-1. Get the
raw value
assigned to the field and return the value of thedata
attribute of field2-2. Get the raw value assigned to the field and return the value of the
value
attribute of field2-3. Get the
dictionary
assigned to the fields