简体   繁体   English

多项选择Django复选框形式验证

[英]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. 我有一个带有favourite_trees字段的表单,我希望它的3个选择显示为复选框。 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. 然后,我希望用户能够选中0到3个复选框,并保存这些结果。 However, when I try to save my form, the favourite_trees field is just saving as an empty list. 但是,当我尝试保存表单时, favourite_trees字段仅保存为空列表。 The other fields are saving correctly. 其他字段正确保存。 How can I fix it so that the checkboxes checked do save? 如何解决此问题,以便选中的复选框能保存?

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

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. 因为您的favourite_trees字段是具有choicesCharField ,所以它仅将TREE_CHOICES中的一种树类型存储为字符串,因此无法直接使用MultipleChoiceField进行保存。 You should use create a separate model called something like TreeChoice , then change field favourite_trees to a ManyToManyField pointing to that model. 您应该使用创建一个名为TreeChoice的单独模型,然后将字段favourite_trees更改为指向该模型的ManyToManyField

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM