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

Question:

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?

Asked By: scre_www

||

Answers:

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
Answered By: andreas-hofmann

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.

Answered By: Daniel Roseman

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()
Answered By: Dric512

Based on the comment by Daniel earlier in this thread I’ve created a simple script to get the job done. I’m sharing this for readers of this thread who are trying to achieve the same goal. This script will creates a working “manage.py deactivate_user” function.

This is an example reference of your Django app folder structure:

Django folder structure

You want to create the “deactivate_user.py” file and place it in management/commands/deactivate_user.py directory.

from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User

class Command(BaseCommand):
    help = 'Deactivate user in the database'

    def handle(self, *args, **options):
        username = raw_input('Please type the username of the user you want remove: ')
        try:
            user = User.objects.get(username=username)
            user.is_active = False
            user.save()
            print ('User is now deactivated in the database.')
        except User.DoesNotExist:
            print ('Username not found')

Call the script by using “python manage.py deactivate_user” You can also create an “activate_user” script with the same code but instead of user.is_active = False use = True.

Answered By: scre_www

Open Django Shell python manage.py shell

Then run execfile('filename.py')

Answered By: thatzprem

If you’re using Django 1.8+, then another useful option is to write your own script, and call it with manage.py runscript.

For example, you can write a script named db_init.py and put it under utils folder.
Then launch this script with:

python3 manage.py runscript utils.db_init

Reference:
https://django-extensions.readthedocs.io/en/latest/runscript.html

Answered By: Shahar Gino

As Daniel Roseman mentions, OP will want 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

Since the command OP wants to run deals with users, OP wants to place it in the user app. Create in the user app a management/commands directory. That’s the place where OP is going to have all of the custom commands of that app. A good name for the file with the command is delete_user_from_database.py. It should look like this

app/
    init.py
    models.py
    management/
        init.py
        commands/
            init.py
            delete_user_from_database.py
    tests.py
    views.py

Then, paste the following code inside of the previously created file (management/commands/delete_user_from_database.py)

from django.core.management.base import BaseCommand
from user. models import User

class Command(BaseCommand):
    help = 'Delete user from database'

    def add_arguments(self, parser):
        parser.add_argument('username', type=str, help='username of the user to delete')

    def handle(self, *args, **kwargs):
        username = kwargs['username']
        usr = User.objects.get(username=username)
        usr.delete()

If one doesn’t want to really delete the user but, instead, make the user inactive, then in the previous code change

usr.delete()

to

usr.is_active = False
usr.save()

Save the file and one can see one’s newly created command in the list of the existing commands by running

python manage.py help

Now assuming we want to delete a user with the username goncaloperes, then we can simply run

python manage.py delete_user_from_database goncaloperes

Read more about Django custom management commands

Answered By: Gonçalo Peres