[英]Django: Denying model saves based on particular criteria
I have a Django model, that is incredibly simple:我有一个 Django model,非常简单:
class Person(models.Model):
name = models.CharField(max_length=100)
I want to deny saving of this model if the actual name changes, but I want to allow changes to capitalisation.如果实际名称发生变化,我想拒绝保存这个 model,但我想允许更改大写。 So for example:
例如:
SAM -> sAm: allowed
Sam -> SAM: allowed
Sam -> John: not allowed
How can I override the save()
method of my Person model so that such edits are denied?如何覆盖我的 Person model 的
save()
方法,以便拒绝此类编辑? Particularly, I'm struggling with:特别是,我正在努力解决:
save()
method.save()
方法中获取 object 的预保存版本。 Feel free to answer any part of the question on its own, and thanks in advance!请随意单独回答问题的任何部分,在此先感谢您!
This answer has two good methods to detect whether a field has changed and do something. 这个答案有两个很好的方法来检测一个字段是否已经改变并做一些事情。
In your case you'd modify it to not just detect if a field has changed but also detect if it's a change you want to allow.在您的情况下,您将修改它以不仅检测字段是否已更改,还检测它是否是您想要允许的更改。
I would use a form and some custom validation in the "clean" method:我会在“干净”方法中使用表单和一些自定义验证:
example:例子:
class MyForm(ModelForm):
class Meta:
model = MyModel
def clean(self):
cleaned_data = self.cleaned_data
name = cleaned_data.get("name ")
if name == ###:
#custom validition checking here
raise forms.ValidationError('You can only capitalize.')
return cleaned_data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.