多项选择Django复选框表格验证

时间:2015-12-16 14:45:22

标签: python django forms

我有一个带有favourite_trees字段的表单,我希望将其3个选项显示为复选框。然后,我希望用户能够检查0到3的复选框,并保存这些结果。但是,当我尝试保存表单时,favourite_trees字段只是保存为空列表。其他字段正确保存。如何修复它以便选中的复选框可以保存?

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 个答案:

答案 0 :(得分:1)

由于您的favourite_trees字段是CharField choices,因此它只在TREE_CHOICES中将一种树存储为字符串,您不能直接使用{{1}保存它。您应该创建一个名为MultipleChoiceField的单独模型,然后将字段TreeChoice更改为指向该模型的favourite_trees

答案 1 :(得分:1)

还有一个包django-multiselectfield可以帮助您存储不需要单独模型的多个(字符串)值。