When should you use TypedChoiceField with a coerce function over a ChoiceField with a clean method on the form for the field?
In other words why would you use MyForm over MyForm2 or vice versa. Is this simply a matter of preference?
from django import forms
CHOICES = (('1', 'A'), ('2', 'B'), ('3', 'C'))
class MyForm(forms.Form):
my_field = ChoiceField(choices=CHOICES)
def clean_my_field(self):
value = self.cleaned_data['my_field']
return int(value)
class MyForm2(forms.Form):
my_field = TypedChoiceField(choices=CHOICES, coerce=int)
In this case, our form has four fields: subject , message , sender and cc_myself . CharField , EmailField and BooleanField are just three of the available field types; a full list can be found in Form fields.
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).
The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).
I would use a clean_field
method for doing "heavy lifting". For instance if your field requires non-trivial, custom cleaning and/or type conversion etc. If on the other hand the requirement is straightforward such as coercing to int
then the clean_field
is probably an overkill. TypedChoiceField
would be the way to go in that case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With