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

14,635

Solution 1

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.

Solution 2

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

Solution 3

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()

Solution 4

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.

Share:
14,635
scre_www
Author by

scre_www

..

Updated on July 22, 2022

Comments

  • scre_www
    scre_www over 1 year

    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?

  • Neneil
    Neneil almost 2 years
    That works for me! One Question isn't it possible to run a .py file instead of writing the code inside EOF? When running python manage.py shell < /path/to/my/foo.py I cannot access my models.