How to execute code in the Django shell by an external python script?

scre_www picture scre_www · Jan 4, 2016 · Viewed 13.5k times · Source

What I want to achieve:

I would like to create a python script to deactivate Django users in the database from the CLI. I came up with this:

$ sudo python manage.py shell
>>> user = User.objects.get(username=FooBar)
>>> user.is_active = False
>>> user.save()
>>> exit()

The above code WORKS when I manually enter it manualy command after command. However, I would like to put execute the commands in one .py script like

$ sudo python script.py

Now I've tried diffirent aproaches:

  • os.system("command1 && command2 && command3")
  • subprocess.Popen("command1 && command2 && command3", stdout=subprocess.PIPE, shell=True)

The problem:

This does not work! I think this problem is here because Python waits until the opened Django shell (first command) finishes which is never. It doesn't execute the rest of the commands in the script as the first command puts it in Hold.

subprocess.popen can execute commands in a shell but only in the Python shell, I would like to use the Django shell.

Anyone ideas how to access the Django shell with a .py script for custom code execution?

Answer

Daniel Roseman picture Daniel Roseman · Jan 4, 2016

Firstly, you should not be accessing your Python shell with sudo. There's no need to be running as root.

Secondly, the way to create a script that runs from the command prompt is to write a custom manage.py script, so you can run ./manage.py deactivate_users. Full instructions for doing that are in the documentation.