Coerce in django forms
django, django-forms, python
Solution
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.
Problem
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.