1

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)

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.