Django ValidationError在视图中?!不是形式

时间:2015-09-25 08:42:17

标签: python django

我在验证Django Form时遇到问题,因为我无法在清理之前保存模型。我有预订型号:

class Reservation(models.Model):
    from = models.DateTimeField()
    to = models.DateTimeField()
    total_price = models.DecimalField()
    paid = models.DecimalField()

    def calculate_price(self):
        self.total_price = some_magic(self.from, self.to)

并形成:

class ReservationForm(forms.ModelForm):
    payment_amount = forms.DecimalField()

    class Meta:
        model = Reservation

    def clean(self):
        ????

我想用clean方法验证payment_amount是否大于total_price但是total_price没有更新 - 我在保存模型后调用calculate_price()。

我可以在计算价格后在视图中提出ValidationError吗?

1 个答案:

答案 0 :(得分:1)

您可以考虑将calculate_price的内容放入一个不会修改预留模型实例数据的方法中。

例如,目前你有假装函数some_magic。在clean你可以这样做:

def clean(self):
    data = super(ReservationForm, self).clean()
    total_price = some_magic(data.get('from'), data.get('to'))
    if data.get('payment_amount') > total_price:
        raise ValidationError("Payment amount should not exceed total price of $%s" % total_price)
    return data

这个想法是通过将其保存在模型上的行为来解开价格计算的计算,以便可以在多个地方使用它(即模型保存方法表单验证)。

相关问题