Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypedChoiceField or ChoiceField in Django

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)
like image 948
hekevintran Avatar asked Sep 09 '10 04:09

hekevintran


People also ask

How many types of Django forms are there?

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.

What is cleaned data in Django?

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).

How do you make a field not required in Django?

The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).


1 Answers

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.

like image 131
Manoj Govindan Avatar answered Oct 07 '22 00:10

Manoj Govindan