在Django-admin中断言值的总和

时间:2010-02-03 21:52:58

标签: django django-admin

我有一件毛衣的Django模型,希望能够输入管理面板中使用的材料成分(例如:“100%羊毛”或“50%羊毛,50%棉”或“50%羊毛” ,45%棉,5%丙烯酸“)。

我有这个型号:

class Sweater(models.Model):
         wool   = models.IntegerField(max_length=3, default=100, verbose_name="wool (%)")
         cotton = models.IntegerField(max_length=3, default=0, verbose_name="cotton (%)")
         acryl  = models.IntegerField(max_length=3, default=0, verbose_name="acryl (%)")

我如何以及在何处断言羊毛,棉花和亚克力值的总和必须为100,以便使用者无法输入例如“100%羊毛,100%棉,100%丙烯酸”?

2 个答案:

答案 0 :(得分:2)

你应该至少在两个地方做这件事。一个是为了确保你没有在模型中得到不正确的数据,一个让用户知道总和不能达到100%。下面处理在表单清理期间检查总和:

class SweaterForm(ModelForm):
    """Form for adding and updating sweaters."""

    def clean(self):
        cleaned_data = self.cleaned_data
        wool = cleaned_data.get('wool')
        cotton = cleaned_data.get('cotton')
        acryl = cleaned_data.get('acryl')

        # Check that the fabric composition adds up to 100%
        if not 'wool' in self._errors \
                and not 'cotton' in self._errors \
                and not 'acryl' in self._errors \
                and (wool + cotton + acryl) != 100:
            msg = u"Composition must add up to 100%!"
            self._errors['wool'] = ErrorList([msg])

            # Remove field from the cleaned data as it is no longer valid
            del cleaned_data['wool']

        return cleaned_data

    class Meta:
        model = Sweater

希望有所帮助!

答案 1 :(得分:1)

在Django的开发版本中,您可以编写a form validator,然后在一个字段上使用“validator_list”参数指定它。

如果您使用的是Django 1.1或更低版本,则可以按建议in the answer to this question覆盖ModelForm。

您可以阅读有关表单验证的更多信息in the documentation