0

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:

  1. Gaining access the pre-save version of the object in the save() method.
  2. Showing a message to the user within Django's admin area when a save is denied.
  3. Returning a user back to the edit screen when a save is denied.

Feel free to answer any part of the question on its own, and thanks in advance!

Sam Starling
  • 5,298
  • 3
  • 35
  • 52

2 Answers2

1

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.

Community
  • 1
  • 1
Greg
  • 45,306
  • 89
  • 231
  • 297
  • Thanks, one of the answers there works really nicely. Do you know of any way to pass a nice message back to the user interface from the `save()` method? It doesn't look like you can use the in-built messages in Django, as you don't have access to the `request` object. – Sam Starling Apr 06 '12 at 19:57
  • @Sam `save()` could be invoked w/o `request`, for example in Python shell, its not the right place to access request inside `save`. – okm Apr 07 '12 at 06:09
0

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
James R
  • 4,571
  • 3
  • 30
  • 45