[Django]-Run shell_plus through PyCharm?

25πŸ‘

I got the model objects auto-loading by hooking into the shell_plus code. I appended this to the default startup script in Preferences > Build, Execution, Deployment > Console > Django Console:

from django_extensions.management import shells
from django.core.management.color import color_style
imported_items = shells.import_objects({}, color_style())
for k, v in imported_items.items():
    globals()[k] = v

This was on PyCharm 2018.3.3 Pro

For completeness, this was the full content of starting script:

import sys; print('Python %s on %s' % (sys.version, sys.platform))
import django; print('Django %s' % django.get_version())
sys.path.extend([WORKING_DIR_AND_PYTHON_PATHS])
if 'setup' in dir(django): django.setup()
import django_manage_shell; django_manage_shell.run(PROJECT_ROOT)

from django_extensions.management import shells
from django.core.management.color import color_style
imported_items = shells.import_objects({}, color_style())
for k, v in imported_items.items():
    globals()[k] = v
πŸ‘€chrisbunney

17πŸ‘

I’ve been looking for a solution to the same problem, and I ended up here. I tried solutions proposed by others, but none of those appeared to solve this issue. So I decided to find another solution. This is what I came up with:

The code block below is the original Django Console starting script of PyCharm 2019.2:

import sys, django
print('Python %s on %s' % (sys.version, sys.platform))
print('Django %s' % django.get_version())
sys.path.extend([WORKING_DIR_AND_PYTHON_PATHS])
if 'setup' in dir(django):
    django.setup()
import django_manage_shell
django_manage_shell.run(PROJECT_ROOT)

Installing IPython and changing the last two lines as below gets it done in the most proper way:

from IPython.core.getipython import get_ipython
ipython = get_ipython()
from django_extensions.management.notebook_extension import load_ipython_extension
load_ipython_extension(ipython)

To make it work: open PyCharm settings (CTRL+S) and head to Django Console section. Then make changes in Starting script window and apply. Finally, start the new Python Console instance.

πŸ‘€Sencer H.

12πŸ‘

I looked at the source code of shell_plus, and noticed you could use a method on a Command class named get_imported_objects({})

In PyCharm, go to: Build, Execution, Deployment > Console > Django Console > Starting script

Add this to the existing code in that box:

from django_extensions.management.commands.shell_plus import Command
globals().update(Command().get_imported_objects({}))

Note: you may have to restart PyCharm to see the effect.

πŸ‘€Jarad

4πŸ‘

One way to solve this is to create a new Python run configuration. Set the target to module, and select the manage.py file for the project. Then put shell_plus in the Parameters field. Set the Working Directory to the project directory. Then lastly, set the Execution to Run with Python Console. Apply the changes, then run the new configuration.

Screenshot of PyCharm Run/Debug Configurations

πŸ‘€King Leon

2πŸ‘

This isn’t a complete answer, but I found this script that at least loads up all the app models. Put this in Settings > Console > Django Console > Starting script:

import sys
import logging
logging.basicConfig(format="%(levelname)-8s %(asctime)s %(name)s %(message)s", datefmt='%m/%d/%y %H:%M:%S', stream=sys.stdout )
log = logging.getLogger("root")

from django.db.models import get_models
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned

logging.config.dictConfig(settings.LOGGING)
log.debug("Logging has been initialized at DEBUG")
log.setLevel( logging.DEBUG)
log.disabled = False

for _class in get_models():
    if _class.__name__.startswith("Historical"): continue
    log.debug("Registering model {}".format(_class.__name__))
    globals()[_class.__name__] = _class

def debug_sql():
    from debug_toolbar.management.commands import debugsqlshell
    return

I also submitted this a feature request to JetBrains.

1πŸ‘

In Django 1.7, following script can be used as a workaround with PyCharm 3.4:

File -> Settings -> Console -> Django Console and manage.py options

In Starting script, put:

import sys
import django
django.setup()

from django.db.models import get_models

for _class in get_models():
    globals()[_class.__name__] = _class
πŸ‘€SaeX

1πŸ‘

django shell run config

This configuration works for me

πŸ‘€Just trying

0πŸ‘

As django.db.models.get_models no longer exists, here’s an updated version that will accomplish the same as Christopher Mason’s version.

import sys; print('Python %s on %s' % (sys.version, sys.platform))
import django; print('Django %s' % django.get_version())
import logging
logging.basicConfig(format="%(levelname)-8s %(asctime)s %(name)s %(message)s", datefmt='%m/%d/%y %H:%M:%S', stream=sys.stdout )
log = logging.getLogger("root")

from django.apps import apps
from django.conf import settings  
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned

logging.config.dictConfig(settings.LOGGING)
log.debug("Logging has been initialized at DEBUG")
log.setLevel( logging.DEBUG)
log.disabled = False

for _configs in apps.get_app_configs():
    for _class in _configs.get_models():
        if _class.__name__.startswith("Historical"): continue
        log.debug("Registering model {}".format(_class.__name__))
        globals()[_class.__name__] = apps.get_model(_configs.label, _class.__name__)

def debug_sql():
    from debug_toolbar.management.commands import debugsqlshell
    return
πŸ‘€ilikerobots

Leave a comment