Alex Rivera | Logout

Make a Django model read-only?

Asked 2010-12-02T10:44:14.297
17

What it says on the tin. Is there a way to make a Django model read-only?

By this I mean a Django model in which once records have been created, they can't be edited.

This would be useful for a model that records transaction history.

Edit
Report

1 Answer

2

You can override the save method and not call super if you wanted to. That'd be a fairly easy way of accomplishing this.

# blatantly ripped the save from another answer, since I forgot to save original model
def save(self, *args, **kwargs):
    if self.id is None:
        super(ModelName, self).save(*args, **kwargs)

def delete(self, *args, **kwargs):
    return

You should probably also raise an exception if a delete or update is attempting to occur instead of simply returning. You want to signal the user what is happening - that the behaviour isn't valid.

answered 2010-12-02T10:50:02.643

Your Answer