43

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?

fastmultiplication
  • 2,951
  • 1
  • 31
  • 39
Jason Swett
  • 43,526
  • 67
  • 220
  • 351

3 Answers3

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