gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:29:22 35 4
gpt4 key购买 nike

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

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com