我有一个CustomModel带有IntegerField 的模型。
class CustomModel(models.Model):
count = models.IntegerField()
Run Code Online (Sandbox Code Playgroud)
当我CustomModel在admin中创建一个新实例时,我必须进行验证,因此我使用该clean方法并可以访问其中的值。
def clean(self):
value = self.count
...
Run Code Online (Sandbox Code Playgroud)
我的问题:
当我更改CustomModel的实例时,我只能访问更改后的新值,而不能访问原始值。但是,为了进行验证,我必须将新值与实例被编辑之前的值进行比较。
我找不到如何获得访问权限的解决方案。有人知道吗
为什么不利用ModelForm?表单数据保存分为两个步骤:
因此,当您有表格时:
class YourForm(forms.ModelForm):
class Meta:
model = CustomModel
fields = ['count',]
def clean(self):
cleaned_data = super(self).clean()
count = cleaned_data.get('count')
if count < self.instance.count:
self.add_error('count', 'You cannot decrease the counter')
return cleanded_data
Run Code Online (Sandbox Code Playgroud)
然后,您可以在管理站点中覆盖表单django。
| 归档时间: |
|
| 查看次数: |
667 次 |
| 最近记录: |