How to reload modules in django shell?

2019-01-30 03:06发布

I am working with Django and use Django shell all the time. The annoying part is that while the Django server reloads on code changes, the shell does not, so every time I make a change to a method I am testing, I need to quit the shell and restart it, re-import all the modules I need, reinitialize all the variables I need etc. While iPython history saves a lot of typing on this, this is still a pain. Is there a way to make django shell auto-reload, the same way django development server does?

I know about reload(), but I import a lot of models and generally use from app.models import * syntax, so reload() is not much help.

9条回答
做自己的国王
2楼-- · 2019-01-30 03:16

Not exactly what you want, but I now tend to build myself management commands for testing and fiddling with things.

In the command you can set up a bunch of locals the way you want and afterwards drop into an interactive shell.

import code

class Command(BaseCommand):
  def handle(self, *args, **kwargs):
     foo = 'bar'
     code.interact(local=locals())

No reload, but an easy and less annoying way to interactively test django functionality.

查看更多
家丑人穷心不美
3楼-- · 2019-01-30 03:21

look at the manage.py shell_plus command provided by the django-extensions project. It will load all your model files on shell startup. and autoreload your any modify but do not need exit, you can direct call there

查看更多
女痞
4楼-- · 2019-01-30 03:22

My solution to it is I write the code and save to a file and then use:

python manage.py shell < test.py

So I can make the change, save and run that command again till I fix whatever I'm trying to fix.

查看更多
不美不萌又怎样
5楼-- · 2019-01-30 03:24

It seems that the general consensus on this topic, is that python reload() sucks and there is no good way to do this.

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-30 03:26

I recommend using the django-extensions project like stated above by dongweiming. But instead of just 'shell_plus' management command, use:

manage.py shell_plus --notebook

This will open a IPython notebook on your web browser. Write your code there in a cell, your imports etc. and run it.

When you change your modules, just click the notebook menu item 'Kernel->Restart'

There you go, your code is now using your modified modules.

查看更多
对你真心纯属浪费
7楼-- · 2019-01-30 03:28

Reload() doesn't work in Django shell without some tricks. You can check this thread na and my answer specifically:

How do you reload a Django model module using the interactive interpreter via "manage.py shell"?

查看更多
登录 后发表回答