12

In shell_plus, is there a way to automatically import selected helper methods, like the models are?

I often open the shell to type:

proj = Project.objects.get(project_id="asdf")

I want to replace that with:

proj = getproj("asdf")
Brett Thomas
  • 1,694
  • 3
  • 15
  • 21

2 Answers2

20

Found it in the docs. Quoted from there:

Additional Imports

In addition to importing the models you can specify other items to import by default. These are specified in SHELL_PLUS_PRE_IMPORTS and SHELL_PLUS_POST_IMPORTS. The former is imported before any other imports (such as the default models import) and the latter is imported after any other imports. Both have similar syntax. So in your settings.py file:

SHELL_PLUS_PRE_IMPORTS = (
    ('module.submodule1', ('class1', 'function2')),
    ('module.submodule2', 'function3'),
    ('module.submodule3', '*'),
    'module.submodule4'
)

The above example would directly translate to the following python code which would be executed before the automatic imports:

from module.submodule1 import class1, function2
from module.submodule2 import function3
from module.submodule3 import *
import module.submodule4

These symbols will be available as soon as the shell starts.

eykanal
  • 26,437
  • 19
  • 82
  • 113
Brett Thomas
  • 1,694
  • 3
  • 15
  • 21
  • I had to change `SHELL_PLUS_PRE_IMPORTS` from a tuple to a list to get it working. – Flash Feb 28 '17 at 13:23
  • 2
    Don't forget the comma if you are importing one item: `SHELL_PLUS_PRE_IMPORTS = ('haystack',)` – Raffi Aug 03 '17 at 21:45
  • 1
    Where do you define SHELL_PLUS_PRE_IMPORTS? Settings.py? – DanGoodrick Feb 05 '20 at 21:04
  • @DanGoodrick yes – Prateek Madhikar Feb 17 '21 at 10:45
  • is there a mechanism to include some imports with aliases? A good use-case would be for the very-common aliases for data science related, like: `import numpy as np`, `import pandas as pd`, `import matplotlib.pyplot as plt`. EDIT: Sry, should have first looked in the docs: https://github.com/django-extensions/django-extensions/blob/main/docs/shell_plus.rst#configuration – M.Ionut Oct 04 '22 at 14:50
0

ok, two ways:

1) using PYTHONSTARTUP variable (see this Docs)

#in some file. (here, I'll call it "~/path/to/foo.py"

def getproj(p_od):
    #I'm importing here because this script run in any python shell session
    from some_app.models import Project
    return Project.objects.get(project_id="asdf")

#in your .bashrc
export PYTHONSTARTUP="~/path/to/foo.py"

2) using ipython startup (my favourite) (See this Docs,this issue and this Docs ):

$ pip install ipython
$ ipython profile create
# put the foo.py script in  your profile_default/startup directory.
# django run ipython if it's installed. 

$ django-admin.py shell_plus 
Leandro
  • 2,217
  • 15
  • 18
  • Both great - but I want to include this in source control, and as it happens this config is built in - see my answer below – Brett Thomas Oct 09 '13 at 11:25