您可以通过将模型表单字段与排除字段进行比较来验证它吗?应该如何在init上设置排除字段?
class MyModel(models.Model):
amount = models.DecimalField()
balance = models.DecimalField()
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs)
self.balance = ??
super(MyForm, self).__init__(*args, **kwargs)
class Meta:
model = MyModel
fields = ['amount']
def clean_amount(self):
amount = self.cleaned_data['amount']
if not (self.balance > 0 and amount > 0) or (self.balance < 0 and amount < 0):
raise forms.ValidationError(
'Cannot apply a negative amount to a positive balance and vice versa.')
return amount
答案 0 :(得分:1)
使用您正在编辑的实例实例化表单:
instance = MyModel.objects.get(pk=pk)
form = MyForm(instance=instance, data=request.POST)
然后在表单中,您可以通过self.instance
访问余额。您不需要在self.balance
方法中设置__init__
。
def clean_amount(self):
amount = self.cleaned_data['amount']
if not (self.instance.balance > 0 and amount > 0) or (self.instance.balance < 0 and amount < 0)
raise forms.ValidationError(
'Cannot apply a negative amount to a positive balance and vice versa.')
return amount