views:

57

answers:

1

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 = (('A', '1'), ('B', '2'), ('C', '3'))

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)
A: 

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.

Manoj Govindan