python - Django:按从 ModelForm 中排除的字段进行验证

标签 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

最佳答案

使用您正在编辑的实例实例化表单:

instance = MyModel.objects.get(pk=pk)
form = MyForm(instance=instance, data=request.POST)

然后在表单中,您可以通过self.instance访问余额。您不需要在 __init__ 方法中设置 self.balance

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

关于python - Django:按从 ModelForm 中排除的字段进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50100561/

相关文章:

python - Django 在输入链接时创建一个对象

django - 在 Django Forms 中应该测试什么?

Django基于模型实例限制ModelForm中ManyToMany字段的选项

Python 2 maketrans() 函数不适用于 Unicode : "the arguments are different lengths" when they actually are

python - Django XMMS2 : 'module' object has no attribute 'XMMS'

javascript - 图表未根据从 Jquery 收到的值进行更新

python - 找到另一个具有目标路径的文件 - 那个文件在哪里?

Python 初学者循环(寻找素数)

python - 用另一列中的相同行值替换 pandas 数据框列中的值

python - ffmpeg和python的使用