Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 288
scre_www Avatar asked Jan 04 '16 12:01

scre_www


2 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
like image 96
andreas-hofmann Avatar answered Nov 02 '22 21:11

andreas-hofmann


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.

like image 37
scre_www Avatar answered Nov 02 '22 20:11

scre_www