Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaning form data in Django

How can i clean and modify data from a form in django. I would like to define it on a per field basis for each model, much like using ModelForms.

What I want to achieve is automatically remove leading and trailing spaces from defined fields, or turn a title (from one field) into a slug (which would be another field).

like image 283
Josh Hunt Avatar asked Nov 22 '08 05:11

Josh Hunt


People also ask

What is form cleaned data in Django?

form. cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. form. data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).

What is clean method in Django?

The clean() method on a Field subclass is responsible for running to_python() , validate() , and run_validators() in the correct order and propagating their errors. If, at any time, any of the methods raise ValidationError , the validation stops and that error is raised.

How does Django validate form data?

Django provides built-in methods to validate form data automatically. Django forms submit only if it contains CSRF tokens. It uses uses a clean and easy approach to validate data. The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class.

What is form Non_field_errors?

non_field_errors () This method returns the list of errors from Form. errors that aren't associated with a particular field. This includes ValidationError s that are raised in Form. clean() and errors added using Form.


1 Answers

You can define clean_FIELD_NAME() methods which can validate and alter data, as documented here: http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation

like image 75
Alex Gaynor Avatar answered Oct 17 '22 00:10

Alex Gaynor