Django - disable model editing

前端 未结 2 728
Happy的楠姐
Happy的楠姐 2021-01-12 15:55

Is there a way, hopefully without breaking admin, to disable editing existing model instances on the ORM level?

I\'m not talking about removing \'Save\' and \'Save a

2条回答
  •  走了就别回头了
    2021-01-12 16:42

    You could override your model class's save() (do nothing if self.pk) and delete (always do nothing)

    But really, the database level is the safest place for that. For example, in PostgreSQL you could write two simple rules:

    CREATE RULE noupd_myapp_mymodel AS ON UPDATE TO myapp_mymodel
       DO NOTHING;
    CREATE RULE nodel_myapp_mymodel AS ON DELETE TO myapp_mymodel
       DO NOTHING;
    

    Either way, the admin wouldn't know anything about this, so everything still looks editable. See my answer to Whole model as read-only for an attempt at making a model read-only in the admin. For your purposes, keep the add permission as-is, and only declare all fields read-only when not adding.

    EDIT: One reason why overriding delete() in your model class is not safe, is the fact that "bulk delete" (Queryset.delete(), e.g. admin checkboxes action) will not call the individual instances' delete() method, it will go straight to SQL: https://docs.djangoproject.com/en/dev/topics/db/queries/#deleting-objects

提交回复
热议问题