what is cleaned data in django

In Django, cleaned data refers to the processed and validated form input data obtained during the form validation process. The cleaning process involves a series of steps performed on the raw form data to ensure that it adheres to specified validation rules and is suitable for further processing. The primary steps involved in cleaning data in Django are:

  1. Field-Specific Cleaning Methods:
  2. Each form field in Django can define a clean_<fieldname>() method, where <fieldname> is the name of the field. These methods are responsible for validating and cleaning the data specific to that field. They are automatically invoked during the form validation process.

  3. Form.clean() Method:

  4. The form class itself can define a clean() method. This method is called after all the field-specific cleaning methods and is used to perform additional validation that involves multiple fields. Any errors raised during this method are associated with the form as a whole, not tied to a specific field.

  5. Validation and Transformation:

  6. During the cleaning process, each form field's data is validated against its declared constraints, such as required fields, minimum and maximum values, and custom validation functions. If the data does not meet the criteria, a ValidationError is raised.

  7. Cleaning Order:

  8. The cleaning process follows a specific order. First, individual field cleaning methods are executed, and then the clean() method is called. If any errors occur at any stage, they are collected and associated with the corresponding fields or the form as a whole.

  9. Accessing Cleaned Data:

  10. Once the cleaning process is complete without any errors, the cleaned data is accessible through the cleaned_data attribute of the form instance. This attribute is a dictionary containing the cleaned values of each field, using the field names as keys.

  11. Error Handling:

  12. If errors are encountered during the cleaning process, they are stored in the errors attribute of the form instance. This attribute is also a dictionary where keys are field names, and values are lists of error messages associated with those fields.

In summary, cleaned data in Django refers to the processed and validated form input data, achieved through the execution of field-specific cleaning methods, the clean() method, and validation against specified constraints. The cleaned data is then accessible through the cleaned_data attribute of the form instance.