【发布时间】:2011-11-10 02:28:18
【问题描述】:
django 项目中的 Model 和 ModelForm 是这样定义的:
class Consumption(models.Model):
date=models.DateTimeField(default=datetime.now)
product_name=models.ForeignKey(Stock,to_field='product_name')
quantity=models.IntegerField()
customer=models.CharField(max_length=50,null=True,blank=True)
def __unicode__(self):
return self.product_name
class ConsumptionForm(ModelForm):
class Meta:
model=Consumption
def clean_quantity(self):
cleaned_data=self.cleaned_data
product=cleaned_data.get("product_name")
quantity=int(cleaned_data.get('quantity'))
stock=Stock.objects.get(product_name=product)
if quantity > stock.quantity:
raise forms.ValidationError("Not enough stock")
return cleaned_data
其中 Stock 类包含用作消费外键的产品名称,其数量应大于消费数量。
现在的问题是当我输入提交到 ConsumptionForm 时。它在数量字段上给我错误,因为即使在我提供整数之后,该字段也必须是整数。
这可能是什么原因?
【问题讨论】:
标签: python django django-forms validation