I created a form class based on a model:
class MyModel(models.Model):
increasing_field = models.PositiveIntegerField()
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
I created a form to change an existing MyClass instance using POST
data to populate the form:
m = MyModel.objects.get(pk=n)
f = MyForm(request.POST, instance=m)
Every time f is being updated, f.increasing_field can only be greater
than the previous value.
How do I enforce that validation?
1 way I can think of is to have clean_increasing_field take on an extra
argument that represents the previous value of increasing_field:
def clean_increasing_field(self, previous_value)
...
This way I can just make sure the new value is greater than the
previous value. But it looks like clean_() methods cannot
take on extra arguments.
Any ideas on how to carry out this validation?
Since the original model has not been updated by the time the validation is done, you could simply look at the current (unchanged) value using “self.instance.increasing_value” (or whatever your field is called). Compare this to the new value being validated, and raise an error if it’s not higher than the current value.
Note: self.instance will return the underlying Model to which the ModelForm is bound.