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

2019-03-10 13:11发布

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.

7条回答
Deceive 欺骗
2楼-- · 2019-03-10 13:37

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.:

class BlankIntField(forms.IntegerField):
    def clean(self, value):
        if not value:
            value = 0
        return int(value)

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:

def clean(self):
    if self.cleaned_data.get('total',-1) <= 0.0:
        raise forms.ValidationError("'Total must be positive")
    return self.cleaned_data

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)

查看更多
仙女界的扛把子
3楼-- · 2019-03-10 13:39

You can use

form.data['field_name']

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

查看更多
冷血范
4楼-- · 2019-03-10 13:44

You can use this pattern:

class MyForm(forms.Form):
    ...
    def clean(self):
        self.saved_data=self.cleaned_data
        return self.cleaned_data

In your code:

if form.is_valid():
    form.save()
    return django.http.HttpResponseRedirect(...)
if form.is_bound:
    form.saved_data['....'] # cleaned_data does not exist any more, but saved_data does.

Using form.data is not a good solution. Reasons:

  • If the form has a prefix, the dictionary keys will be prefixed with this prefix.
  • The data in form.data is not cleaned: There are only string values.
查看更多
女痞
5楼-- · 2019-03-10 13:47

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.

查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-03-10 13:47

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()
查看更多
Explosion°爆炸
7楼-- · 2019-03-10 13:49

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", '')
        ...
查看更多
登录 后发表回答