How to reload Django shell without restarting?
Django shell is perhaps the first place where developers test their code and verify all the functionality. But we generally don't develop the whole code in the shell. most of the time we copy-paste the whole function and execute. Though this way of development is perfect for say 20-30 lines maximum, we struggle when the number of lines increases.
All of us would have always wanted to what if we could reload the content of the .py
files which we recently updated in the IDE without exiting the existing shell. The solution to this problem becomes much easier. When you use ipython
, IPython is a great interactive shell which is a great alternative to the regular python shell.
Let us see how we can reload Django code without restarting the whole shell.
- Install IPython
pip install Ipython
- Enter the Django shell
python manage.py shell
- Whenever you need to reload a particular code for a given file or function block the use the
reload(<module name>)
function fromfrom importlib import reload
to reload the newest content which is being updated in the current codebase.
For example
>>> from events import public
>>> public.hello_world()
Hello world
#### Now you go to the IDE and update the code inside hello_world function
>>> from importlib import reload
>>> reload(public)
>>> public.hello_world()
this is new hello world