1

我正在围绕模型进行一项简单的调查:

模型.py

class Fruits(models.Model):
     author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
     title = models.CharField(max_length=200, default='')
     text = models.TextField(default='')
     banana = models.BooleanField(default=False)
     grape = models.BooleanField(default=False)
     apple = models.BooleanField(default=False)
     mango = models.BooleanField(default=False)

表格.py

class FruitPicker(ModelForm):
    class Meta:
        model = Fruits
        fields = [
        'title',
        'text',
        'banana',
        'grape',
        'apple',
        'mango'
    ]
    
    widgets = {
        'text': forms.Textarea(attrs={"style": "height:10em;" "width:60em;"}),
        'banana': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}),
        'grape': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}),
        'apple': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}),
        'mango': forms.CheckboxInput(attrs={"style": "margin-left:350px;"})
    }

现在假设我想确保用户必须选择最少 2 个水果,但最多选择 3 个。我将如何在后端执行此操作?

4

1 回答 1

1

您可以覆盖clean表单的方法以检查是否检查了两个到三个BooleanFields:

from django.core.exceptions import ValidationError

class FruitPicker(ModelForm):
     # ⋮

    def clean(self, *args, **kwargs):
        data = super().clean(*args, **kwargs)
        total = sum([data[x] for x in ['banana', 'grape', 'apple', 'mango']])
        if not (2 <= total <= 3):
            raise ValidationError('You should select between 2 and 3 fruits.')
        return data

这里sum(…)总结了booleans 和使用0for False,以及 1 for True,因此它计算了Trues 的数量。如果该数字不在 和 之间23则引发ValidationError

于 2021-10-27T14:11:25.327 回答