[Fixed]-How to execute code in the Django shell by an external python script?

15đź‘Ť

âś…

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.

8đź‘Ť

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

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

2đź‘Ť

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.

👤scre_www

1đź‘Ť

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

👤Shahar Gino

0đź‘Ť

Open Django Shell python manage.py shell

Then run execfile('filename.py')

👤thatzprem

0đź‘Ť

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

Leave a comment