Make Django model read-only?

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

By this, I mean the Django model, in which, after creating the records, they cannot be edited.

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

+13
django django-models
02 Dec '10 at 10:44
source share
4 answers

You can override the method of saving the model and check if it is an existing object, in which case you will not save any changes:

def save(self, *args, **kwargs): if self.id is None: super(ModelName, self).save(*args, **kwargs) 

Thus, in this example, you save changes only when the object has not yet received id , but this is only the case when it has not yet been inserted.

+9
Dec 02 '10 at
source share

You can override the save method and not call super if you want. This will be a fairly easy way to do 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 throw an exception if an attempt to delete or update occurs instead of simply returning. You want to tell the user what is happening - that the behavior is invalid.

+3
Dec 02 '10 at 10:50
source share

In addition to other solutions: If your main goal is to avoid access to the record from the administrator, you can change the administrator class used so that no one has the right to add / change:

 class HistoryAdmin(admin.ModelAdmin): def has_add_permission(self, request): return False def has_change_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj=None): return False 
+3
Dec 02 '10 at 11:22
source share

If you do not want the write attempt to write to be unsuccessful:

 def save(self, *args, **kwargs): if self.pk: (raise an exception) super(YourModel, self).save(*args, **kwargs) def delete(self, *args, **kwargs): (raise an exception) 
+1
Apr 03 '15 at 12:56
source share



All Articles