I have a Django model, that is incredibly simple:
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. 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? Particularly, I'm struggling with:
save()
method.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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.