I have a model CustomModel
with an IntegerField.
JavaScript
x
3
1
class CustomModel(models.Model):
2
count = models.IntegerField()
3
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.
JavaScript
1
4
1
def clean(self):
2
value = self.count
3
4
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?
Advertisement
Answer
Why not take advantage of a ModelForm
? Form data is saved in two steps:
- To the form instance
- To the model instance
So when you have a form:
JavaScript
1
15
15
1
class YourForm(forms.ModelForm):
2
3
class Meta:
4
model = CustomModel
5
fields = ['count']
6
7
def clean(self):
8
cleaned_data = super().clean()
9
count = cleaned_data.get('count')
10
11
if count < self.instance.count:
12
self.add_error('count', 'You cannot decrease the counter')
13
14
return cleanded_data
15
You can then override the form within the django
admin site.