I have a model CustomModel with an IntegerField.
class CustomModel(models.Model):
count = models.IntegerField()
When I create a new instance of CustomModel in the admin, I have to do validation, so I use the clean method and have access to the value with.
def clean(self):
value = self.count
...
My problem:
When I change the instance of CustomModel, I only have access to the new, changed value but not to the original value. However, for my validation I have to compare the new value and the value before the instance got edited.
I could not found a solution how to get access. Does somebody know?
Why not take advantage of a ModelForm? Form data is saved in two steps:
So when you have a form:
class YourForm(forms.ModelForm):
class Meta:
model = CustomModel
fields = ['count']
def clean(self):
cleaned_data = super().clean()
count = cleaned_data.get('count')
if count < self.instance.count:
self.add_error('count', 'You cannot decrease the counter')
return cleanded_data
You can then override the form within the django admin site.
There's also a solution just using the model:
def clean(self):
if self.pk:
previous_count = self.__class__.objects.get(pk=self.pk).count
else:
previous_count = None # If saving a new instance
self.__class__ access the model class and fetch the currently stored .count value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With