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

Try to input the commands to the running django-shell as a here document:

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

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.


If you want to execute a Python script that accesses Django models, you first need to set an environment variable:

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<path>.settings")

In which you need to replace <path> by your project directory, the one that contains the file settings.py.

You can then import your model files, for example:

from <path>.models import User
user = User.objects.get(username=FooBar)
user.is_active = False
user.save()