Monday, July 30, 2012

How to add formatted per-field errors : Override the .clean() method of a Django Form/ModelForm.

Only can do it this way, and not anymore in the View function. -__-"

Scenario:

You used JavaScript to selectbox:onchange() to:
1. insert a <input hidden name="sth" value="nth"> hidden field with name="sth" and value="nth".
2. submit POST the Django form.

3. You want to show a form field's errmsg.
You have to override the form object's .clean() method (called on a call to is_valid() in the view),
BUT, you can't get the request object in that method. SO:

# You can't get the request object in form.clean method.
# So just try to 'get' from cleaned_data, your inserted <input hidden> from the form.


    def clean(self):
        cleaned_data = super(ProductEditForm, self).clean()

##        print "cleaned data EditForm", cleaned_data
        # No choice, even non-form request.GET or POST['hidden_lang_change'] data has to be checked here.
        # If you want to even put anything in self.field._errors = [some list of errmsgs,]

        print "===" # You can't get the request object in form.clean method.
        print cleaned_data.get('lang') # So just try to 'get' from cleaned_data, your inserted <input hidden> from the form.
        print cleaned_data.get('lancau')
        print "---"

        if cleaned_data.get('hidden_lang_change'):
            pass
        else:
            # purposely set field error
            errmsg = "purposely set field error"
            self._errors["lang"] = self.error_class([errmsg])
            pass

        return cleaned_data



##############################EXAMPLE PRINTOUT:
in the View, this line: print "is_valid()=", self.product_edit_form.is_valid()

Gives the below printout:


is_valid()= ===
en
None
---
False


=== : call to form.is_valid() starts. The '===' prints out first.
The '---' prints out last.
The actual return value of is_valid is printed; it is False. because of the form error that you purposely made.

No comments:

Post a Comment