Ashutosh Verma
Ashutosh Verma

Reputation: 11

is there any Switch which can disable/enable for any changes in django model objects?

Is there anything like switch/flag available in Django models which can enable/disable for any changes.

by enabling this switch, you can not change/delete any model object even in referenced models (connected with foreign key) not even from Django-shell.

Upvotes: 1

Views: 288

Answers (2)

Amit
Amit

Reputation: 2108

Since you are asking for stopping insert for even Django shell, I can think of one way. There must be more elegant methods. Please note I have not tried it myself but my suggestion is based on the information present here. So it might be a good idea to wait for far more experienced members of Stackoverflow.

I have assumed you are using MySQL. Please change the suggestion below to suit your DBMS.

For this to happen, you need admin rights to the database with GRANT privileges. Also suppose your Django user name in SETTINGS.py is 'abcdef' (in the database section) and the table you want to restrict is 'mytable' and the database is 'mydatabase'. I am also assuming that you want it to happen for access from any IP.

Basically you will have to revoke insert/delete rights as below.

REVOKE INSERT, DELETE ON mydatabase.mytable FROM 'abcdef'@'%';

You can repeat the process for other privileges.

To enable you need to GRANT the same privileges as below.

GRANT INSERT, DELETE ON mydatabase.mytable TO 'abcdef'@'%';

Please let me know if this is what you wanted.

Upvotes: 1

Iain Shelvington
Iain Shelvington

Reputation: 32244

You could use multiple database connections which are actually just 2 connections to the same DB just with different users. One with full permissions and the other with only read permissions

settings.py

DATABASES = {
    'default': {
        'NAME': 'foo',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'superuser',
        'PASSWORD': 'superuser',
    },
    'restricted': {
        'NAME': 'foo',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'restricted',
        'PASSWORD': 'restricted',
    }
}

Then add a custom database router that switches between the 2

class SwitchRouter:

    def _writes_disabled(self):
        return False  # or True if the "switch" has been triggered somehow

    def db_for_write(self, model, **hints):
        if self._writes_disabled():
            return 'restricted'

settings.py

DATABASE_ROUTERS = ['path.to.SwitchRouter']

Upvotes: 3

Related Questions