Reputation: 6127
Can you validate a model form field by comparing it to an excluded field? How should the excluded field be set on 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
Upvotes: 1
Views: 125
Reputation: 309099
Instantiate the form with the instance you are editing:
instance = MyModel.objects.get(pk=pk)
form = MyForm(instance=instance, data=request.POST)
Then in the form, you can access the balance via self.instance
. You don't need to set self.balance
in the __init__
method.
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
Upvotes: 1