gpt4 book ai didi

python - 通过 clean 方法传递时 django modelform 字段上的错误验证错误

转载 作者:太空宇宙 更新时间:2023-11-04 09:17:28 25 4
gpt4 key购买 nike

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 类包含作为 Consumption 外键的产品名称,其数量应大于消费数量。

现在的问题是当我输入 submit to ConsumptionForm 时。它在数量字段上给我错误,因为即使在我为其提供整数之后,该字段也必须是整数。

这可能是什么原因?

最佳答案

您将从 clean_quantity 方法返回整个 cleaned_data 字典,而不仅仅是 quantity 的值。

关于python - 通过 clean 方法传递时 django modelform 字段上的错误验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7299547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com