Forms in Django(bound, unbound, clean, is_valid, errors)
Bound and Unbound Forms:
- Form Instance is either bound to a set of data, or unbound.
- If it is bound to a set of data, it is capable of validating that data and rendering the form as HTML with the data displayed in the HTML.
- If it is unbound, it cannot do validation, because there’s no data to validate, but it can still render the blank form as HTML.
- To create an unbound Form instance, instantiate the class:
sf = SampleForm()
- To bind data to a form, pass the data as a dictionary as the first parameter to your Form class constructor:
data = {'fieldname1': 'ABC', 'fieldname2': 'True, 'fieldname3': '123'}
sf = SampleForm(data)
- In the above dictionary, the keys are the field names, which correspond to the attributes in your Form class and the values are the data you are trying to validate. These will usually be strings, but there is no requirement that they be strings; the type of data you pass depends on the Field.
Form.is_bound attribute:
When the requirement is distinguish between bound and unbound form instances at runtime, check the value of the form’s is_bound attribute:
Ex1: sf = SampleForm()
sf.is_bound
Result: False
Ex2: sf = SampleForm({'fieldname1': 'ABC'})
sf.is_bound
Result: True
- Note: Passing an empty dictionary creates a bound form with empty data:
sf = SampleForm({})
sf.is_bound
Result: True
- When you want to change bound Form instance data, or if you want to bind an unbound Form instance to some data, create another Form Instance.
- There is no possible way to change data in a Form instance.
- Once a Form instance has been created, you should consider its data immutable, whether it has data or not.
Form.clean():
- Implement a clean() method on your Form when you must add custom validation for fields that are interdependent.
- The primary task of a Form object is to validate data.
- With a bound Form instance, call the is_valid() method to run validation and return a boolean designating whether the data is valid.
Form.errors:
- Access the errors attribute to get a dictionary of error messages:
sf.errors
Ex: {'fieldname1': ['This field is required']}
- In this dictionary, the key(s) are the field names, and the values are lists of strings representing the error messages. The error messages are stored in lists because a field can have multiple error messages.
- You can access errors without having to call is_valid() first. The form’s data will be validated the first time whether you call is_valid() or access errors.
- The validation routines will only get called once, regardless of how many times you access errors or call is_valid(). This means that if validation has side effects, those side effects will only be triggered once.
Form.errors.as_data():
- Returns a dictionary that maps fields to their original ValidationError Instances. sf.errors.as_data()
{'fieldname1': [ValidationError(['This field is required.'])],
'fieldname2': [ValidationError(['Enter a valid email address.'])]}- Use this method anytime you need to identify an error by its code. This enables things like rewriting the error’s message or writing custom logic in a view when a given error is present.
- It can also be used to serialize the errors in a custom format (e.g. XML); for instance, as_json() relies on as_data().
- The need for the as_data() method is due to backwards compatibility. Previously ValidationError instances were lost as soon as their rendered error messages were added to the Form.errors dictionary.
Comments
Post a Comment