I'm tired of typing from account_import.models import ImportFile
every time I open my Django shell. Is there a way to automatically run this command whenever I fire up my shell?
Asked
Active
Viewed 1.9k times
43

fastmultiplication
- 2,951
- 1
- 31
- 39

Jason Swett
- 43,526
- 67
- 220
- 351
3 Answers
67
install django-extensions, one of the commands it features (shell_plus) is providing the context for your models. https://github.com/django-extensions/django-extensions
So, instead of ./manage.py shell
you can use ./manage.py shell_plus
so that everything is imported.

Sachin Singh
- 7,107
- 6
- 40
- 80

Uku Loskit
- 40,868
- 9
- 92
- 93
-
Hmm. I installed django-extensions but it said `Unknown command: 'shell_plus'` when I tried to do `./manage.py shell_plus`. – Jason Swett Feb 04 '11 at 20:36
-
7Don't forget to add 'django_extensions' to your INSTALLED_APPS – David Dehghan Sep 23 '11 at 05:35
-
2and do you know such SHELL which will keep track of all updates which happen to the database in real time without need for restarting? – andilabs Feb 04 '14 at 16:21
-
That's right, add 'django_extensions' to INSTALLED_APPS, _not_ 'django-extensions' -- underscore, not hyphen. – elimisteve May 08 '14 at 20:04
8
http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP
If you set the environment variable PYTHONSTARTUP
to a file, this will be run first whenever you start a python shell.

Daren Thomas
- 67,947
- 40
- 154
- 200
-
oh, ok. I didn't know about django's shell. But django is definitly on my list of stuff to check out! – Daren Thomas Feb 02 '11 at 14:13
-
it loaded the file but didn't load it within the same namespace/context of the shell. disclaimer: i'm python&django newbie – Leo Gallucci Feb 11 '14 at 13:41
-
This actually worked perfectly in my case. I use virtualenvs. In the `postactivate` script, I added an alias to first export the `PYTHONSTARTUP` variable, then run the django shell. The startup script only executes when I use this alias. The only downside is if I run this alias, then in the same terminal, close the django shell, and try to open normal python shell, it will read the startup file again. But I never do this anyway. So I can live with it. – Shashwat Black Jul 05 '18 at 23:34
-
Finally an answer that doesn't require to install additional components. For the record you need to create a file imports.py like `from myapp.models import *`. Then launch the shell with this `PYTHONSTARTUP="imports.py" python3 manage.py shell` – LatinSuD Jul 23 '21 at 08:41
0
Create a file.py
file in the same directory as manage.py
file with all imports that you need.
For example:
from django.core.cache import cache; from django.db.models import Prefetch, Count, Q; from django.db import connection, reset_queries; from datetime import timedelta; from django.utils import timezone;
Then, every time after you launch the shell, simply import that file: from file import *

Serguei A
- 334
- 1
- 2
- 10