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

家住魔仙堡 提交于 2019-12-02 19:52:39
Dmitry Risenberg

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.

Sam

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", '')
        ...

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.

I ran into a similar problem using a formset. In my example, I wanted the user to select a 1st choice before a 2nd choice, but if the 1st choice hit another error, the 'select 1st choice before 2nd' error was also displayed.

To grab the 1st field's uncleaned data, I used this within the form field's clean method:

dirty_rc1 = self.data[self.prefix + '-reg_choice_1']

Then, I could test for the presence of data in that field:

if not dirty_rc1:
    raise ValidationError('Make a first choice before second')

Hope this helps!

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!