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.


You can use

form.data['field_name']

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


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.


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:

form_name['field_name'].value()

I have many methods. All you can pick.

I suppose the form is like as below:

class SignupForm(forms.Form):
    email = forms.CharField(label='email')
    password = forms.CharField(label='password',
                               widget=forms.PasswordInput)

1-1. Get from request

def signup(req):
    if req.method == 'POST':
        email = req.POST.get('email', '')
        password = req.POST.get('password', '')

2-1. Get the raw value assigned to the field and return the value of the data attribute of field

def signup(req):
    if req.method == 'POST':
        ...
        sf = SignupForm(req.POST)
        email = sf["email"].data
        password = sf["password"].data
        ...

2-2. Get the raw value assigned to the field and return the value of the value attribute of field

def signup(req):
    if req.method == 'POST':
        ...
        sf = SignupForm(req.POST)
        email = sf["email"].value()
        password = sf["password"].value()
        ...

2-3. Get the dictionary assigned to the fields

def signup(req):
    if req.method == 'POST':
        ...
        sf = SignupForm(req.POST)
        # print sf.data
        # <QueryDict: {u'csrfmiddlewaretoken': [u'U0M9skekfcZiyk0DhlLVV1HssoLD6SGv'], u'password': [u''], u'email': [u'hello']}>
        email = sf.data.get("email", '')
        password = sf.data.get("password", '')
        ...