【问题标题】:Wrong validation error on a django modelform field when passed through clean method通过 clean 方法时 django modelform 字段上的错误验证错误
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您无需将cleaned_data.get('quantity') 类型转换为int。表单基类上的 Django 的 to_python() 方法将为您完成此操作。作为验证过程的一部分,所有表单都会尝试将其值转换为 Python 值。

      我没有在你的 clean_quantity() 方法中看到任何让我认为它不起作用的东西,尽管你没有显示你的 Stock 类,所以我们可以看到什么类型的字段 stock.quantity 是.

      我的建议是为此表单和视图方法编写一个单元测试,以确保您获得正确的值。 https://docs.djangoproject.com/en/1.3/topics/testing/

      如果您没有编写单元测试的习惯,现在是开始的好时机。它们确实可以为您节省大量时间。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-15
        • 2019-08-15
        • 2014-04-05
        • 2011-04-21
        • 2019-08-08
        • 2021-10-28
        • 1970-01-01
        相关资源
        最近更新 更多