我在验证 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):
????
我想在干净的方法中验证 payment_amount 是否不大于total_price 但total_price 未更新 - 我在保存模型后调用calculate_price()。
价格计算后我可以在 View 中引发 ValidationError 吗?
最佳答案
您可以考虑将 calculate_price
的内容放入不修改 Reservation 模型实例数据的方法中。
例如,目前您有假装函数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
这个想法是将价格计算的计算与将其保存在模型上的行为分开,以便它可以在多个地方使用(即模型保存方法或表单验证)。
关于python - Django ValidationError View 中?!不形成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32778187/