orange1
orange1

Reputation: 2939

Multiple Choice Django Checkbox Form Validation

I have a form with a favourite_trees field, which I would like to have its 3 choices show up as check boxes. I'd then like for the user to be able to check 0 to 3 of the check boxes, and to have those results be saved. However, when I try to save my form, the favourite_trees field is just saving as an empty list. The other fields are saving correctly. How can I fix it so that the checkboxes checked do save?

forms.py

class TreesForm(forms.models.ModelForm):
    favourite_trees = forms.MultipleChoiceField(choices=TreePreference.TREE_CHOICES,
        widget=forms.CheckboxSelectMultiple())
    class Meta:
        model = TreePreference
        fields = (
                'tree_knowledge',
                'tree_type',)
        widgets = {
            'tree_type': forms.HiddenInput(),
        }

models.py

class TreePreference(models.Model):
    TREE_CHOICES = ('red_trees',
                    'blue_trees',
                    'purple_trees',
                   )
    tree_knowledge = model.CharField(blank=True, max_length=10)
    tree_type = model.CharField(blank=True, max_length=20)
    favourite_trees = models.CharField(choices=TREE_CHOICES, max_length=50, blank=True)

Upvotes: 1

Views: 1231

Answers (2)

Lorenzo Peña
Lorenzo Peña

Reputation: 2263

There is also a package django-multiselectfield that might help you with storing multiple (string) values that do not require a separate model.

Upvotes: 1

Shang Wang
Shang Wang

Reputation: 25559

Because your favourite_trees field is a CharField with choices, so it only stores one type of tree in TREE_CHOICES as a string, you cannot directly use MultipleChoiceField to save it. You should use create a separate model called something like TreeChoice, then change field favourite_trees to a ManyToManyField pointing to that model.

Upvotes: 1

Related Questions