我有一个毛衣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%丙烯“?
发布于 2010-02-04 06:29:59
你应该至少在两个地方这样做。一个是为了确保您不会在模型中获得不正确的数据,另一个是为了让用户知道总和不是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希望这能有所帮助!
发布于 2010-02-04 06:29:41
在Django的开发版本中,您可以编写a form validator,然后在其中一个字段上使用"validator_list“参数指定它。
如果你使用的是Django1.1或更低版本,你可以按照建议的in the answer to this question重写ModelForm。
您可以阅读有关表单验证in the documentation的更多信息。
https://stackoverflow.com/questions/2195757
复制相似问题