Django:通过ModelForm排除的字段进行验证

时间:2018-04-30 12:28:23

标签: python django django-forms

您可以通过将模型表单字段与排除字段进行比较来验证它吗?应该如何在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

1 个答案:

答案 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