Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coerce in django forms

What does the coerce argument do in django forms? I've read the documentation, but its not very helpful, so a good explanation with a few examples of use cases would be helpful. To quote the documentation:

A function that takes one argument and returns a coerced value. Examples include the built-in int, float, bool and other types. Defaults to an identity function.

like image 933
Games Brainiac Avatar asked Aug 13 '13 04:08

Games Brainiac


1 Answers

TypedChoiceField is just like ChoiceField, except ChoiceField always return unicode.

With TypedChoiceField you pass a function that takes one argument and returns the value cast to the type you want. For example, if you want to coerce the value to integer, use:

int_field = forms.TypedChoiceField(choices=SOME_CHOICES, coerce=int)

The field value will always be an integer or fail validation.

like image 68
Paulo Scardine Avatar answered Sep 30 '22 07:09

Paulo Scardine